生产消费者

生产消费者

AQS
是个抽象类。里面定义了同步器的基本框架,实现了基本的结构功能。只留有状态条件的维护由具体同步器根据具体场景来定制,如常见的 ReentrantLock 、 RetrantReadWriteLock和CountDownLatch

Condition是在java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition的await()、signal()这种方式实现线程间协作更加安全和高效。因此通常来说比较推荐使用Condition,阻塞队列实际上是使用了Condition来模拟线程间协作。

    public static void main(String[] args) throws IOException {

        AtomicInteger goi = new AtomicInteger();
        ExecutorService executorService = Executors.newCachedThreadPool();
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition conP = reentrantLock.newCondition();
        Condition conC = reentrantLock.newCondition();
        ArrayBlockingQueue<Integer> goods = new ArrayBlockingQueue(10);

        executorService.submit(() -> {
            while (true) {
                reentrantLock.lock();
                if (goods.size() == 10) {
                    try {
                        System.out.println("仓库已满,等待被消费");
                        conP.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                int i = goi.getAndIncrement();
                goods.add(i);

                System.out.println("仓库 补货 ..." + i);
                conC.signalAll(); //消费者可以消费了
                reentrantLock.unlock();
            }
        });

        executorService.submit(() -> {

            while (true) {
                reentrantLock.lock();
                if (goods.size() == 0) {
                    try {
                        conC.await(); //没有货物,消费者停止
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int n = goods.poll(); //消费开始,库存不满,

                System.out.println("消费者消费 " + n);
                conP.signalAll(); //生产者可以开始生产了
                reentrantLock.unlock();
            }
        });

        System.in.read();
    }
原文地址:https://www.cnblogs.com/snow-man/p/14529038.html