package Test;
public class Clerk {
//-1表示目前没有产品
private int product = -1;
//这个方法由生产者调用
public synchronized void setProduct(int product){
if(this.product != -1){
try{
//目前店员没有空间收产品,请稍后!
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.product = product;
System.out.printf("生产者设定 (%d)%n",this.product);
//通知等待区的一个消费者可以继续工作了
notify();
}
//这个方法由消费者调用
public synchronized int getProduct(){
if(this.product == -1){
try{
//缺货了,请稍后!
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
int p = this.product;
System.out.printf("消费者取走了 (%d)%n" , this.product);
this.product = -1;//取走产品,-1表示目前店员手上无产品
//通知等待区的一个生产者可以继续工作了
notify();
return p;
}
}