您的位置:首页 > 其它

线程间通信-多生产者多消费者

2016-07-14 20:49 246 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  生产者消费者