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();
}
}
}
线程间通信-多生产者多消费者
最新推荐文章于 2025-03-15 17:52:33 发布
本文提供了一个使用Java实现的生产者消费者模式示例。通过多线程技术,模拟了两个生产者线程不断生产商品,同时两个消费者线程消费这些商品的过程。该示例利用了synchronized关键字和wait/notifyAll方法来确保线程间的同步。
1763

被折叠的 条评论
为什么被折叠?



