程序背景:100只蜜蜂生产蜂蜜,每次生产1,两只熊消耗蜂蜜,每次消耗20,
生产的蜂蜜放在Box中,最大容量为20。
public class ThreadDemo7{
public static void main(String[] args){
Box box = new Box();
for(int i=0; i<100; i++){
new Bee("Bee-"+i, box).start();
}
new Bear("Bear-1", box).start();
new Bear("Bear-2", box).start();
}
}
class Bee extends Thread{
private String name;
private Box box;
public Bee(String name, Box b){
this.name = name;
this.box = b;
}
public void run(){
while(true){
int i = box.add();
System.out.println(this.name + "生产了蜂蜜,总数:" + i);
}
}
}
class Bear extends Thread{
private String name;
private Box box;
public Bear(String name, Box b){
this.name = name;
this.box = b;
}
public void run(){
while(true){
box.remove();
System.out.println(this.name + "消耗了蜂");
}
}
}
class Box{
private final int Max = 20;
private int count = 0;
public synchronized int add(){
while(count >= Max){
try{
this.notify(); //方法执行完后释放锁旗标。
this.wait(); //立即释放锁旗标。
}
catch(Exception e){
}
}
return ++count;
}
public synchronized void remove(){
while(count < Max){
try{
this.wait();
}
catch(Exception e){
}
}
count = 0;
this.notify();
}
}