Learn from Synchronized and BlockingQueue

来源:互联网 发布:知乎 万历郑贵妃 编辑:程序博客网 时间:2024/06/06 01:56

The producer and consumer model:


Object has a value that intent to be produced by producer and consumed by consumer.

Object also has produce method which used byProducer and consume method  which used by Consumer.


usage of BlockingQueue in the producer-consumer model:

http://www.java3z.com/cwbwebhome/article/article20/200030.html?id=4852


Because thread.stop() is unsafe, so we should avoid the use of it.

Instead, we use ExecutorService.submit() and ExecutorService.shutdownNow()


</pre><pre name="code" class="html">Basket basket = new Basket();Runnable producer = new Producer(basket);Runnable consumer = new Consumer(basket);ExecutorService service = Executors.newCachedThreadPool();service.submit(producer);service.submit(consumer);try {<span style="white-space:pre"></span>Therad.sleep(7000);} catch (InterruptedException e) {<span style="white-space:pre"></span>e.printStackTrace();}service.shutdownNow();}




0 0
原创粉丝点击