public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss=new SyncStack();
Producer pro=new Producer(ss);
Consumer con=new Consumer(ss);
new Thread(pro).start();
new Thread(pro).start();
new Thread(con).start();
}
}
class Product{
int id;
public Product(int id){
this.id=id;
}
public String toString(){//重写toString 方法,给pro加上编号,以便调试
return "product "+id;
}
}
class SyncStack{//栈,先进后出
Product[] proArr=new Product[6];//定义容器只能装6件产品
int index=0;
public synchronized void push(Product pro){
while(index==proArr.length){//当容器装满了产品,暂停生产
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notifyAll();//唤醒消费者消费
proArr[index]=pro;
index++;
}
public synchronized Product pop(){//同步,确保不被打断
while(index==0){//当容器里没有产品可消费,暂停消费
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notifyAll();//唤醒生产者生产
index--;
return proArr[index];
}
}
class Producer implements Runnable{
SyncStack ss=null;
public Producer(SyncStack ss){
this.ss=ss;
}
public void run() {
for(int i=0;i<20;i++){
Product pro=new Product(i);
ss.push(pro);
System.out.println("生产了:"+pro);
try{//方便观察结果,没有实际意义
Thread.sleep((int)(Math.random()*200));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
SyncStack ss=null;
public Consumer(SyncStack ss){
this.ss=ss;
}
public void run(){
for(int i=0;i<20;i++){
Product pro=ss.pop();
System.out.println("消费了:"+pro);
try{//方便观察结果,没有实际意义
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}