class ProducerConsumerDemo {
public static void main(String[] args){
Resource resource = new Resource();
//多个生产者,多个消费者
new Thread(new Producer(resource)).start();
new Thread(new Producer(resource)).start();
new Thread(new Consumer(resource)).start();
new Thread(new Consumer(resource)).start();
}
}
class Resource {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name){
while(flag)
try{wait();}catch (Exception e){}
this.name = name + "--" +count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out(){
while(!flag)
try{wait();}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r = r;
}
public void run(){
while(true){
r.set("+商品+");
}
}
}
class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}