package javaapplication3;
/**
*多线程多消费及其解决
* 问题1:重复生产,重复消费;原因:被唤醒的线程没有判断标记就开始工作(生产0r消费)了
* 解决:被唤醒的线程必须被判断标记
* 使用while循环判断标记
* 问题2:死锁,所有的线程都处于冻结状态;原因:本方线程在唤醒时,又一次唤醒了本方线程,
* 而本方线程循环判断标记,继续的等待导致所有的线程店都等待
* 解决:使用notifyAll()方法
*
* 实现了多生产多消费的功能但是唤醒了本方线程浪费了CPU,效率不高
* @author tf
*/
class Res
{
private String name;
private int count=1;
private boolean flag;
public synchronized void set(String name)
{
while(flag)
try{this.wait();}catch(InterruptedException e){}
this.name=name+"---"+count;
count++;
System.out.println(Thread.currentThread().getName()+".....生产者....."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void get()
{
while(!flag)
try{this.wait();}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+".....消费者....."+this.name);
flag=true;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Res r;
Producer (Res r)
{
this.r=r;
}
public void run()
{
r.set("面包");
}
}
class Consumer implements Runnable
{
private Res r;
Consumer(Res r)
{
this.r =r;
}
public void run()
{
r.get();
}
}
public class JavaApplication3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Res r=new Res();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t0=new Thread(pro);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
Thread t3=new Thread(con);
t0.start();
t1.start();
t2.start();
t3.start();
}
}