道招

java多线程生产者消费者例子

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

java多线程生产者消费者例子

java多线程一章里面举了一个很经典的例子,它就是生产者和消费者的例子,比如说有一个篮子,里面能放6个饼,有厨师生产饼子,顾客吃饼子,厨师生产一个就往篮子里面放,放满的话,线程暂停,提醒顾客快吃;顾客一次吃一个饼子,如果篮子空了,线程也暂停,提醒厨师继续生产。 ProducerConsumer.java的源代码如下 [code lang="java"] package com.daozhao.java.thread; public class ProducerConsumer { public static void main(String[] args){ Basket b=new Basket(); Producer p=new Producer(b); Consumer c=new Consumer(b); new Thread(p).start(); new Thread(c).start(); } } class WoTou{ int id; WoTou(int id){ this.id=id; } public String toString(){ return "WoTou:" + id; } } class Basket{ int index=0; WoTou[] arrWT=new WoTou[6]; public synchronized void push(WoTou wt){ while(index == arrWT.length){ try{ this.wait(); }catch(InterruptedException i){ i.printStackTrace(); } } this.notify(); arrWT[index]=wt; index++; } public synchronized WoTou pop(){ while(index==0){ try{ this.wait(); }catch(InterruptedException i){ i.printStackTrace(); } } this.notify(); index--; return arrWT[index]; } } class Producer implements Runnable{ Basket b=null; Producer(Basket b){ this.b=b; } public void run(){ for(int i=0;i<20;i++){ WoTou wt=new WoTou(i); b.push(wt); i++; System.out.println("生产了"+ wt); try{ Thread.sleep(2000); }catch(InterruptedException ie){ ie.printStackTrace(); } } } } class Consumer implements Runnable{ Basket b=null; Consumer(Basket b){ this.b=b; } public void run(){ for(int i=0;i<20;i++){ WoTou wt=b.pop(); System.out.println("消费了" + wt); try{ Thread.sleep(1000); }catch(InterruptedException ie){ ie.printStackTrace(); } } } } [/code]
更新时间:
上一篇:道招网近期出现无法访问下一篇:多玩歪歪yy申述系统真是不行

相关文章

关注道招网公众帐号
友情链接
消息推送
道招网关注互联网,分享IT资讯,前沿科技、编程技术,是否允许文章更新后推送通知消息。
允许
不用了