public class Consume_Produce {
public static void main(String[] args ){
Bullet b=new Bullet();
Produce p=new Produce(b);
Consume c=new Consume(b);
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.start();
t2.start();
}
}
class Bread{
public int id;
public Bread(int id){this.id=id;}
}
class Bullet {
Bread b[]=new Bread[15];
public int index=0;//bread的id
public synchronized void produceBread(){
while(index==15){ //l篮子的容量是15,当达到15个面包时 生产线程wait
try{this.wait();
}catch(InterruptedException e)
{e.printStackTrace();}
}
this.notify(); //唤醒别的线程
b[index]=new Bread(index);
index++;
System.out.println("produce-----"+index);
}
public synchronized Bread consumeBread(){
while(index==0){ //当篮子里面没有面包时,消费线程wait()
try{this.wait();
}catch(InterruptedException e)
{e.printStackTrace();}
}
this.notify(); //唤醒别的线程
System.out.println("consume-----"+index);
index--;
return b[index];
}
}
class Produce implements Runnable{ //这是一个生产线程
Bullet b=null;
public Produce(Bullet b){this.b=b;}
public void run(){
for(int i=0;i<200;i++){
b.produceBread();}
}
}
class Consume implements Runnable{ //这是一个消费线程
Bullet b=null;
public Consume(Bullet b){this.b=b;}
public void run(){
for(int i=0;i<200;i++){ b.consumeBread();}
}
}