![]() ![]() |
|
JAVA技巧(Java线程间的通信) | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/10/22 21:35:55 文章录入:杜斌 责任编辑:杜斌 | |
|
|
线程间的通信(生产者-消费者模式) 下面的代码实现了本案例:
class Producer extends Thread{ Panel pan = null; Consumer c = null; public Producer(Panel pan, Consumer c){ this.pan = pan; this.c = c; } public void run(){ synchronized(c){ int count = 0; //Examda提示: 生产者一共要生产100个桔子 while(count++ < 100){ if(!pan.isBlank){ try{c.wait();}catch(Exception ex){ex.printStackTrace();} } int orgWeight = (int)(Math.random() * 100); Orange org = new Orange(orgWeight, "red"); pan.putOrange(org); c.notify(); } } } } class Consumer extends Thread{ Panel pan; public Consumer(Panel pan){ this.pan = pan; } public void run(){ synchronized(this){ while(true){ if(pan.isBlank){ try{wait();}catch(Exception ex){ex.printStackTrace();} } pan.getOrange(); notify(); } } } } class Orange{ int weight; String color; public Orange(int weight, String color){ this.weight = weight; this.color = color; } public String toString(){ return "Orange, weight = " + weight + ", color = " + color; } } class Panel{ public boolean isBlank = true; private Orange org; public void putOrange(Orange org){ this.org = org; isBlank = false; System.out.println("I put: " + org.toString()); } public Orange getOrange(){ System.out.println("I get: " + org.toString()); isBlank = true; return org; } } www.Examda.CoM |
|
![]() ![]() |