java多线程 消费者问题_java多线程经典问题-------生产者、消费者问题

hotDogs = new ArrayList

(); //热狗集合 public static void main(String[] args) { for(int i = 1;i<4;i++){ new Thread(new Producer(i)).start(); } for(int j = 1;j<5;j++){ new Thread(new Consumer(j)).start(); } try { Thread.sleep(5000); System.exit(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static class Producer implements Runnable{ private int pid = -1; int i = 1; //标识热狗编号 public Producer(int pid) { this.pid = pid; } @Override public void run() { /** * 生产者生产热狗,只要有热狗生产出来就可以唤醒所有的等待线程, * 热狗数量超过了展示台5个,就等待消费 */ while(true){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//模拟生产消耗时间 synchronized(hotDogs){ if(hotDogs.size() < 5){ //添加热狗--生产 hotDogs.add(pid*100+i); System.out.println(pid+"号热狗师傅生产"+pid*100+i+"号热狗"); i++; //有了热狗就可以叫消费者来吃 hotDogs.notifyAll(); }else{ System.out.println("热狗拷满了,快来吃啊!"); try { hotDogs.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//等待 } } } } } static class Consumer implements Runnable{ private int cid = -1; public Consumer(int cid) { this.cid = cid; } @Override public void run() { /** * 消费者者生产热狗,只要消费了热狗就可一唤醒所有等待进程, * 热狗数量超过了展示台5个,就等待生产 */ while(true){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//模拟生产消耗时间 synchronized(hotDogs){ if(hotDogs.size() > 0){ //添加热狗--生产 System.out.println("消费者" + this.cid + "正在消费一个热狗,其编号为:" + hotDogs.remove(0)); //有了热狗就可以叫消费者来吃 hotDogs.notifyAll(); }else{ System.out.println("热狗mei了,快点做啊!"); try { hotDogs.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//等待 } } } } } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值