生产者消费者问题--BlockingQueue
# 代码: public class App { public static void main(String[] args) { BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(6); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); producer.produce(5); consumer.consume(4); producer.produce(3); consumer.consume(2); } } class Producer { private BlockingQueue<Integer> queue; public Producer(BlockingQueue<Integer> queue) { this.queue = queue; } public void produce(final int val) { new Thread() { public void run() { try { int surplus = val; while (surplus > 0) { queue.put(1024); surplus--; System.out.printf("%s plan to produce (%d),actually produce (%d),queue size (%d) n",Thread.currentThread().getName(),val,1,queue.size()); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } } class Consumer { private BlockingQueue<Integer> queue; public Consumer(BlockingQueue<Integer> queue) { this.queue = queue; } public void consume(final int val) { new Thread() { public void run() { int surplus = val; try { while (surplus > 0) { queue.take(); surplus--; System.out.printf("%s plan to consume (%d),actually consume (%d),queue.size()); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } } ? # 输出: Thread-0 plan to produce (5),actually produce (1),queue size (1) # 有四个线程参与了这个过程,两个生产者,两个消费者 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 学习Java中的日期和时间处理及Java日历小程序的编写
- 如何处理实例化类对象时发生的异常
- Java类的继承:Java简单的继承及单继承和多继承的区别
- 错误“由以下引起:java.lang.ClassNotFoundException:”
- 在Java中解析JSON对象数组
- Java bug?无法直接使用Scanner读取GB2312文件
- java – Hibernate – hibernate.hbm2ddl.auto = validate
- java – 如何控制Tomcat可用的SSL密码
- Java GC概念:CMSInitiatingOccupancyFraction
- java – 由于任务尝试无法报告状态600秒而导致reduce失败.杀