/*
需求:
多生产,多消费
思路:
步骤:
*/
class Resource
{
private String name;
private int num = 1;
private boolean flag;
public synchronized void set(String name)
{
//对于多生产者,此处需要用while来判断,如果不用while的话,当线程被唤醒后
//不去判断标记,直接生产可能会存在问题,导致之前生产的不会被消费
while(flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
this.name = name + num;
System.out.println(Thread.currentThread().getName() + "...生产者..." + this.name);
num++;
flag = true;
//另外这里需要改为notifyAll();因为notify是任意唤醒一个线程,假设唤醒的依然是生产者
//会导致所有线程处于等待状态
//notify();
notifyAll();
}
public synchronized void out()
{
//对于多生产者,此处需要用while来判断,如果不用while的话,当线程被唤醒后
//不去判断标记,直接消费可能会存在问题,导致之前生产的会被消费多次
while(!flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
System.out.println("-------"+ Thread.currentThread().getName() + "... 消费者..." +name);
//num--;
flag = false;
//另外这里需要改为notifyAll();因为notify是任意唤醒一个线程,假设唤醒的依然是消费者
//会导致所有线程处于等待状态
//notify();
notifyAll();
}
}
class Producer implements Runnable
{
private Resource r;
public Producer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.set("烤鸭");
}
}
}
class Consumer implements Runnable
{
private Resource r;
public Consumer(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class MultiProducerConsumer
{
public static void main(String[] args)
{
Resource r = new Resource();
Producer pro1_runnable = new Producer(r);
Producer pro2_runnable = new Producer(r);
Consumer con1_runnable = new Consumer(r);
Consumer con2_runnable = new Consumer(r);
Thread pro1_thread = new Thread(pro1_runnable);
Thread pro2_thread = new Thread(pro2_runnable);
Thread con1_thread = new Thread(con1_runnable);
Thread con2_thread = new Thread(con2_runnable);
pro1_thread.start();
pro2_thread.start();
con1_thread.start();
con2_thread.start();
}
}