package cn.edu.hdu.chenpi.cpdemo.howtodoinjava;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;public class ProducerConsumerExample { public static void main(String[] args) throws InterruptedException { int numProducers = 4; int numConsumers = 3; BlockingQueue myQueue = new LinkedBlockingQueue<>(20); for (int i = 0; i < numProducers; i++) { new Thread(new Producer(myQueue)).start(); } for (int i = 0; i < numConsumers; i++) { new Thread(new Consumer(myQueue)).start(); } // Let the simulation run for, say, 10 seconds Thread.sleep(10 * 1000); // End of simulation - shut down gracefully System.exit(0); }}
当我们运行以上代码,会发现类似如下输出结果:
Consumed resource - Queue size now = 1Produced resource - Queue size now = 1Consumed resource - Queue size now = 1Consumed resource - Queue size now = 1Produced resource - Queue size now = 1Produced resource - Queue size now = 1Produced resource - Queue size now = 1Consuming object java.lang.Object@14c7f728Consumed resource - Queue size now = 0Consuming object java.lang.Object@2b71e323Consumed resource - Queue size now = 0Produced resource - Queue size now = 0Produced resource - Queue size now = 1Produced resource - Queue size now = 2Consuming object java.lang.Object@206dc00bConsumed resource - Queue size now = 1Produced resource - Queue size now = 2Produced resource - Queue size now = 3Consuming object java.lang.Object@1a000bc0Consumed resource - Queue size now = 2Consuming object java.lang.Object@25b6183dConsumed resource - Queue size now = 1Produced resource - Queue size now = 2Produced resource - Queue size now = 3......Produced resource - Queue size now = 20Consuming object java.lang.Object@2b3cd3a6Consumed resource - Queue size now = 19Produced resource - Queue size now = 20Consuming object java.lang.Object@3876982dConsumed resource - Queue size now = 19Produced resource - Queue size now = 20