生产者消费者
2015-11-18 10:22
357 查看
class Source { private int num = 0; public synchronized void increase() { while(num != 0) { try { wait(); } catch(Exception e) { e.printStackTrace(); } } num++; System.out.println(num); notify(); } public synchronized void decrease() { while(num == 0) { try { wait(); } catch(Exception e) { e.printStackTrace(); } } num--; System.out.println(num); notify(); } } class Producer implements Runnable{ private Source source; Producer(Source source) { this.source = source; } public void run() { for(int i=0; i<10; i++) { /*try { Thread.sleep((long)Math.random()*1000); } catch(Exception e) { e.printStackTrace(); }*/ source.increase(); } } } class Consumer implements Runnable{ private Source source; public Consumer(Source source) { this.source = source; } public void run() { for(int i=0; i<10; i++) { /*try { Thread.sleep((long)Math.random()*1000); } catch(Exception e) { e.printStackTrace(); }*/ source.decrease(); } } } public class Mian { public static void main(String[] args) { Source s = new Source(); new Thread(new Producer(s)).start(); new Thread(new Consumer(s)).start(); } }
相关文章推荐
- Lua编程示例(八):生产者-消费者问题
- 深入多线程之:深入生产者、消费者队列分析
- Ruby实现生产者和消费者代码分享
- java解决单缓冲生产者消费者问题示例
- 【扫盲】史上最全的互联网专业词语汇总!
- 解读小米模式:颠覆式创新者的背后
- 实现灵活的IT架构的三个要点
- 三星Gear Fit讨人喜欢的5点之一
- 谷歌投200万$奖安全研究者 找到两千多项漏洞并修复
- 比较简洁易懂的云计算及其运行模式的解读
- 大数据拼精准可否触动电商个性营销神经?
- Hibernate关联关系配置(一对多、一对一和多对多)
- 外媒列10大理由建议消费者不购买iPad
- 牛人整理分享的面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- 谷歌扩展其开源承诺
- 云计算
- 淘宝和百度解禁:淘宝客前途堪忧
- 生产者消费者模式的三种实现方式
- Python3 通过 pika 连接 RabbitMQ 的基本用法
- JQuery UI - resizable