Java多线程-生产者消费者问题(多个消费者多个生产者)
public class ConsumerProcuderDemo {
public static void main(String[] args) {
Resourse resourse = new Resourse();//多个线程,共享一个变量,主要注意点就是对这个变量的共享访问控制
new Thread(new Procuder(resourse)).start();//将这个变量传递给每个线程
new Thread(new Procuder(resourse)).start();
new Thread(new Consumer(resourse)).start();
new Thread(new Consumer(resourse)).start();
}
}
class Procuder implements Runnable{
private Resourse res;
public Procuder(Resourse resourse) {
res = resourse;
}
@Override
public void run() {
while(true){
res.set("商品");
}
}
}
class Consumer implements Runnable{
private Resourse res;
public Consumer(Resourse resourse) {
res = resourse;
}
@Override
public void run() {
while(true){
res.out();
}
}
}
class Resourse{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {//多个生产线程的控制
while (flag) {//为false的时候,进行生产,true时,睡眠等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
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 (InterruptedException e) {
e.printStackTrace();
}
}
//count --;
System.out.println(Thread.currentThread().getName() + "-------------消费者-----------" + this.name);
flag = false;
this.notifyAll();
}
}