java 中多线程之间的通讯之生产者和消费者 (多个线程之间的通讯)

在真实开发 中关于多线程的通讯的问题用到下边的例子是比较多的

不同的地方时if 和while 的区别 如果只是两个线程之间的通讯,使用if是没有问题的。

但是在多个线程之间就会有问题

 /*
* 这个例子用来解释多个生产者和多个消费者的情况
*/ /*
* 资源库
*/
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set (String name){ while (flag)
try {this.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 {this.wait();}
catch(Exception e){ }
System.out.println(Thread.currentThread().getName() + "消费了" + this.name);
flag = false;
this.notifyAll();
} } /*
* 生产者
*/
class Producer implements Runnable
{
private Resource res;
Producer (Resource res){ this.res = res;
}
public void run(){ while (true){ res.set ("牙膏");
}
} }
/*
* 消费者
*/
class Consumer implements Runnable
{ private Resource res;
Consumer(Resource res){ this.res = res;
}
public void run(){ while (true){
res.out();
}
}
}
public class producerConsumerDemo { public static void main(String[] args) {
// TODO Auto-generated method stub
Resource res = new Resource(); Producer p1 = new Producer(res);
Producer p2 = new Producer(res); Consumer c1 = new Consumer(res);
Consumer c2 = new Consumer(res); Thread t1 = new Thread(p1);
Thread t2 = new Thread(p2);
Thread t3 = new Thread(c1);
Thread t4 = new Thread(c2); t1.start();
t2.start();
t3.start();
t4.start(); } }
上一篇:在Linux环境下采用压缩包方式安装JDK 13


下一篇:ubuntu采用apt方式安装多个版本php-fpm