JAVA 生产者与消费者

生产者与消费者 满足

  • 自定义同步容器,容器容量上限为10。可以在多线程中应用,并保证数据线程安全。
1,wait()和notifyAll()
public class Test {
        private final LinkedList list = new LinkedList();
        private final int MAX = 10;
        private int count = 0;
        
        public synchronized int getCount() {
            return count;
        }
        
        public synchronized void put(E e) {
            // wait/notify都是和while配合应用的。可以避免多线程并发判断逻辑失效问题。
            while (list.size()==MAX) {
                try {
                    this.wait();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            list.add(e);
            count++;
            this.notifyAll();
        }
        
        public synchronized E get() {
            E e = null;
            // wait/notify都是和while配合应用的。可以避免多线程并发判断逻辑失效问题。
            while(list.size()==0) {
                try {
                    this.wait();
                } catch (InterruptedException ee) {
                    ee.printStackTrace();
                }
            }
            e =list.removeFirst();
            count--;
            this.notifyAll();
            return e;
        }
        
}

2, 使用ReentrantLock 的Condition

public class Test {
    private final LinkedList list = new LinkedList();
    private final int MAX = 10 ;
    private int count = 0;
    
    private Lock lock = new ReentrantLock();        
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();
    
    public int getCount() {
        return count;
    }
    
    public synchronized void put(E e) {
        lock.lock();
        try {
            while(list.size()==MAX) {
                System.out.println("等待...");
                try {
                    // 借助条件,进入的等待队列。
                    producer.await();
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                }
            }
            list.add(e);
            count++;
            // 借助条件,唤醒所有的消费者。
            consumer.signal();
        } catch (Exception e2) {
            e2.printStackTrace();
        }finally {
            lock.unlock();  
        }
    }
    
    public synchronized E get() {
        lock.lock();
        E e = null;
        try {
            while (list.size()==0) {
                try {
                    // 借助条件,消费者进入等待队列
                    consumer.wait();
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            e = list.removeFirst();
            count--;
            // 借助条件,唤醒所有的生产者
            producer.signal();
        } catch (Exception e2) {
            e2.printStackTrace();
        }finally {
            lock.unlock();
        }
        return e;
    }
        
}

你可能感兴趣的:(JAVA 生产者与消费者)