class Product{
private String name;
private int count;
private boolean flag;
public synchronized void produce(String name){
while(flag){
try{wait();}catch(InterruptedException e){e.printStackTrace();}
}
this.name = name+"..."+count;
System.out.println(Thread.currentThread().getName()+"生产了..."+this.name);
count++;
flag = true;
notifyAll();
}
public synchronized void consume(){
while(!flag){
try{wait();}catch(InterruptedException e){e.printStackTrace();}
}
System.out.println(Thread.currentThread().getName()+"...消费了..."+this.name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable{
private Product pro;
public Producer(Product pro){
this.pro = pro;
}
public void run(){
while(true){
pro.produce("笔记本");
}
}
}
class Consumer implements Runnable{
private Product pro;
public Consumer(Product pro){
this.pro = pro;
}
public void run(){
while(true){
pro.consume();
}
}
}
class test{
public static void main(String[] args){
Product pro = new Product();
Producer producer = new Producer(pro);
Consumer consumer = new Consumer(pro);
Thread t0 = new Thread(producer);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
Thread t3 = new Thread(consumer);
t0.start();
t1.start();
t2.start();
t3.start();
}
}