题目:用多线程模拟蜜蜂和熊的关系。
100只蜜蜂是生产者,2只熊是消费者,蜜蜂生产蜂蜜是累加的过程,熊吃蜂蜜是批量(满20吃掉)的过程。生产者与消费者之间是用通信方式告诉对方,注意不能出现死锁的现象。
参考代码:
public class BeeDemo {
public static void main(String[] args){
Box box = new Box();
for(int i=1;i<=100;i++){
new Bee("Bee-"+i,box).start();
}
new Bear("熊大",box).start();
new Bear("熊二",box).start();
}
}
//蜜蜂
class Bee extends Thread{
private String name;
private Box box;
public Bee(String name,Box box){
this.name=name;
this.box=box;
}
public void run(){
while(true){
int n=box.add();
System.out.println(name+"生产了蜂蜜:1,box:"+n);
}
}
}
//熊
class Bear extends Thread{
private String name;
private Box box;
public Bear(String name,Box box){
this.name=name;
this.box=box;
}
public void run(){
while(true){
box.remove();
System.out.println(name+"吃掉了蜂蜜:20 ");
}
}
}
//蜜罐
class Box{
private int MAX=20;
private int count;
//添加蜂蜜加1
public synchronized int add(){
while(count>=MAX){ //这里只能用while而不能用if,因为if只执行一次,而while要求每次都要重新判断
try{
this.notify(); //当蜜罐里的蜂蜜达到最大值20时,蜜蜂就通知熊取蜂蜜
this.wait(); //蜜蜂线程进入等待队列
}
catch(Exception e){
e.printStackTrace();
}
}
return ++count;
}
//移出蜂蜜-MAX
public synchronized void remove(){
while(count<MAX){
try{
this.wait(); //当蜜罐里的蜂蜜不足20时,熊处在等待队列
}
catch(Exception e){
e.printStackTrace();
}
}
count=0;
this.notify(); //熊取完蜂蜜后,通知蜜蜂继续生产蜂蜜
}
}