public class ProduceConsume{
public static void main (String []args){
gt aa=new gt();
Produce pr=new Produce(aa);
Consume co=new Consume(aa);
Thread th1=new Thread(pr);
Thread th2=new Thread(co);
th1.start();
th2.start();
}
}
class Mantou{
int index;
Mantou(int i){
index=i;
}
public String toString(){
return "woto:"+index;
}
}
class gt{
int index=0;
Mantou []mt=new Mantou[20];
public synchronized void push(Mantou a){
while(index==19){
try{ this.wait();
}catch(InterruptedException se) {se.printStackTrace();}
}
this.notify();
mt[index]=a;
index++;
}
public synchronized Mantou pop(){
while(index==0){
try{ this.wait();
}catch(InterruptedException se){se.printStackTrace();}
}
this.notify();
index--;
return mt[index];
}
}
class Produce implements Runnable{
gt aa=null;
Produce(gt aa){
this.aa=aa;
}
public void run(){
for(int i=0;i<20;i++){
Mantou as=new Mantou(i);
aa.push(as);
System.out.println("生成:"+as);
try{
Thread.sleep(4000);
}catch(InterruptedException se){}
}
}
}
class Consume implements Runnable{
gt aa=null;
Consume(gt aa){
this.aa=aa;
}
public void run(){
for(int i=0;i<20;i++){
Mantou dd=aa.pop();
System.out.println("消费:"+dd);
try{
Thread.sleep(1000);
}catch(InterruptedException se){}
}
}
}