package thread;
/**
* 多个生产者,多个消费者
* @author zjw
*
*/
public class Procedure_Customer {
public static void main(String args[]){
Resource r=new Resource();
Procedure p=new Procedure(r);
Customers c=new Customers(r);
Procedure p1=new Procedure(r);
Customers c1=new Customers(r);
//多个生产者,多个消费者
new Thread(p).start();
new Thread(c).start();
new Thread(p1).start();
new Thread(c1).start();
}
}
class Resource{
private String name;
private int count=1;
private boolean boo;
public synchronized void set(String name){
while(boo){
try{
this.wait();
}catch(Exception e){
e.printStackTrace();
}
}
this.name=name+"-----"+count++;
System.out.println("生产:name:"+this.name);
boo=true;
this.notifyAll();
}
public synchronized void out(){
while(!boo){
try{
this.wait();
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println("----消费--------"+name);
boo=false;
this.notifyAll();
}
}
class Procedure implements Runnable{
private Resource r;
public Procedure(Resource r){
this.r=r;
}
public void run(){
while(true){
r.set("aaaa");
}
}
}
class Customers implements Runnable{
private Resource r;
public Customers(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out();
}
}
}