public class Clerk {

private int product=0;//产品默认0;

//生产者生成出来的产品交给店员

public synchronized void addProduct(){

if(this.product>=20){

try {

wait();//产品已满,请稍等在生产

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}

}else{

product++;

System.out.println("生产者生产地"+product+"个产品。");

notifyAll(); //通知等待区的消费者今天取产品了

}

}

//消费者从店员处取产品

public synchronized void getProduct(){

if(this.product<=0){

try {

wait();//产品没有货了,请稍等再取

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}

}else{

System.out.println("消费者取走了第"+product+"个产品");

product--;

notifyAll();//通知等待区的生成者可以生产 产品

}

}

}

//消费者线程要执行的任务

public class Consumer implements Runnable {

private Clerk cl;

  public Consumer(Clerk cl) {

this.cl=cl;

}

  

  

public void run() {

System.out.println("消费者开始取走产品!");

while(true){

try {

Thread.sleep((int)(Math.random()*10)*100);

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}

cl.getProduct();//取走产品

}

}


}

//生产者线程要执行的任务

public class Producer implements Runnable {

private Clerk cl;

public Producer(Clerk cl){

this.cl=cl;

}


public void run() {

System.out.println("生产者开始生产产品!");

while(true){

try {

Thread.sleep((int)(Math.random()*10)*100);

} catch (InterruptedException e) {

// TODO 自动生成的 catch 块

e.printStackTrace();

}

cl.addProduct();//生产产品

}

}

}

public class Main {


public static void main(String[] args) {

// TODO 自动生成的方法存根

Clerk cl=new Clerk();

Thread prt=new Thread(new Producer(cl));//生产者线程

Thread cot=new Thread(new Consumer(cl));//消费者线程

prt.start();

cot.start();

}


}