多个生产者多个消费者,只有5个包子
2015-12-22 00:00
316 查看
摘要: 不是new一个对象调用锁,而是用BaoZi.calss直接调用锁
package com.reveiew; /* * 多个生产者多个消费者,只有5个包子 * 跟第一,第二的例子不同的是,不是new一个对象调用锁,而是用BaoZi.calss直接调用锁 */ public class MoreProuduceCustomMoreBaoZi { public static void main(String[] args) { Produce3 p = new Produce3(); p.setName("生产者"); Produce3 p2 = new Produce3(); p2.setName("生产者2"); Produce3 p3 = new Produce3(); p3.setName("生产者3"); customer3 c = new customer3(); c.setName("消费者"); customer3 c2 = new customer3(); c2.setName("消费者2"); customer3 c3 = new customer3(); c3.setName("消费者3"); p.start(); c.start(); p2.start(); c2.start(); p3.start(); c3.start(); } } class BaoZi3 { public static int num = 0; } class Produce3 extends Thread { public void run() { while (true) { synchronized (BaoZi3.class) { while (BaoZi3.num >=5) { // 等着消费者消费.生产者应该等待。需要用锁去调用wait方法。 try { BaoZi3.class.wait();// wait会释放锁//哪个线程执行就是哪个线程等 } catch (InterruptedException e) { e.printStackTrace(); } } BaoZi3.num++; try { Thread.sleep(1000);// sleep不会释放锁 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "生产一个包子"+"剩余包子"+BaoZi3.num); BaoZi3.class.notifyAll();// 唤醒消费者 } } } } class customer3 extends Thread { public void run() { while (true) { synchronized (BaoZi3.class) { while (BaoZi3.num == 0) { try { BaoZi3.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } BaoZi3.num--; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "消费一个包子"+"剩余包子"+BaoZi3.num); // 唤醒消费者 BaoZi3.class.notifyAll();// 唤醒当前等待的一个线程 } } } }
相关文章推荐
- Lua编程示例(八):生产者-消费者问题
- Ruby实现生产者和消费者代码分享
- java解决单缓冲生产者消费者问题示例
- 【扫盲】史上最全的互联网专业词语汇总!
- 解读小米模式:颠覆式创新者的背后
- 实现灵活的IT架构的三个要点
- 三星Gear Fit讨人喜欢的5点之一
- 谷歌投200万$奖安全研究者 找到两千多项漏洞并修复
- 比较简洁易懂的云计算及其运行模式的解读
- 大数据拼精准可否触动电商个性营销神经?
- Hibernate关联关系配置(一对多、一对一和多对多)
- 外媒列10大理由建议消费者不购买iPad
- 牛人整理分享的面试知识:操作系统、计算机网络、设计模式、Linux编程,数据结构总结
- 谷歌扩展其开源承诺
- 云计算
- 淘宝和百度解禁:淘宝客前途堪忧
- 苹果新一代iPad被指"过热" 测评报告5天后发布
- dpdk 代码分析一 : 内存初始化
- 传统企业电商之路的思考
- 无线“蹭网卡”热卖 任意密码5分钟破解