/**
* 生产者消费者问题.(蜜蜂Bee,熊Bear)
* 蜜蜂产蜜到罐子中,产满进入等待并通知熊大熊二来吃。
* 熊从罐子里吃蜂蜜,罐子不足10L时等待.攒满10L时吃.
* 罐子在某一时刻只能被熊或蜜蜂独占(synchronized同步).
* 由于可能产生死锁,解决方案(1.等待一段时间后重新抢占 2.notifyAll 多人强占)
*/
class Bee extends Thread{
private String name ; //蜜蜂的名字,代号
private java.util.List<Integer> jar ; //蜜罐
final static int MAX = 10 ; //蜜罐的最大容量L
//构造函数
public Bee(String name,java.util.List<Integer> jar){
this.name = name ;
this.jar = jar ;
}
//线程方法
public void run(){
while(true){
synchronized(jar){ //对蜜罐进行独占同步
int size = jar.size();
if(size==MAX){ //如果蜜罐满了,就停止产蜜
try{
jar.notify();
jar.wait();
}
catch(Exception e){
}
}
else{ //蜜罐没满就产蜜并与熊抢占蜜罐
jar.add(new Integer(size+1));
System.out.println(name+"产蜜 +1 总:"+jar.size()+"L");
}
}
yield(); //谦让一下
}
}
}
class Bear extends Thread{
private String name ; //熊的名字,代号
private java.util.List<Integer> jar ; //蜜罐
public Bear(String name, java.util.List<Integer> jar){
this.name = name ;
this.jar = jar ;
}
//线程代码
public void run(){
while(true){
synchronized(jar){ //对蜜罐进行独占同步
int size = jar.size();
if(size < 10){ //如果蜜罐空了就等待
try{
jar.wait();
}
catch(Exception e){
}
}
else{
for(int i = 9 ;i >=0 ; i--){
jar.remove(i);
}
System.out.println(name+"吃蜜 : "+jar.size());
jar.notifyAll(); //notifyAll
try{
jar.wait();
}
catch(Exception e){
}
}
}
yield(); //谦让
}
}
}
class BearEatHoney{
public static void main(String[] args) {
java.util.List<Integer> jar = new java.util.ArrayList<Integer>();
Bear bear1 = new Bear("Bear1",jar);
Bear bear2 = new Bear ("Bear2",jar);
Bee bee1 = new Bee("Bee1",jar);
Bee bee2 = new Bee("Bee2",jar);
Bee bee3 = new Bee("Bee3",jar);
Bee bee4 = new Bee("Bee4",jar);
Bee bee5 = new Bee("Bee5",jar);
Bee bee6 = new Bee("Bee6",jar);
Bee bee7 = new Bee("Bee7",jar);
Bee bee8 = new Bee("Bee8",jar);
Bee bee9 = new Bee("Bee9",jar);
Bee bee10 = new Bee("Bee10",jar);
bear1.start();
bear2.start();
bee1.start();
bee2.start();
bee3.start();
bee4.start();
bee5.start();
bee6.start();
bee7.start();
bee8.start();
bee9.start();
bee10.start();
}
}
结果:
Bee9产蜜 +1 总:1L
Bee4产蜜 +1 总:2L
Bee9产蜜 +1 总:3L
Bee4产蜜 +1 总:4L
Bee8产蜜 +1 总:5L
Bee4产蜜 +1 总:6L
Bee8产蜜 +1 总:7L
Bee2产蜜 +1 总:8L
Bee4产蜜 +1 总:9L
Bee3产蜜 +1 总:10L
Bear1吃蜜 : 0
Bee3产蜜 +1 总:1L
Bee6产蜜 +1 总:2L
Bee3产蜜 +1 总:3L
Bee1产蜜 +1 总:4L
Bee6产蜜 +1 总:5L
Bee7产蜜 +1 总:6L
Bee1产蜜 +1 总:7L
Bee10产蜜 +1 总:8L
Bee7产蜜 +1 总:9L
Bee10产蜜 +1 总:10L
Bear2吃蜜 : 0
Bee8产蜜 +1 总:1L
Bee7产蜜 +1 总:2L
Bee8产蜜 +1 总:3L
Bee1产蜜 +1 总:4L
Bee7产蜜 +1 总:5L
Bee6产蜜 +1 总:6L
Bee8产蜜 +1 总:7L
Bee1产蜜 +1 总:8L
Bee7产蜜 +1 总:9L
Bee3产蜜 +1 总:10L
Bear2吃蜜 : 0