class Produse
{
private String name;
private int counter=1;
private boolean flag=false;
public synchronized void set(String name)
{
if(flag)
{
try
{
wait();
}
catch (Exception a)
{
}
}
this.name=name;
System.out.println(Thread.currentThread().getName()+"///shengchan//////////"+counter);
this.notify();//唤醒
flag=true;//将标志位置真
}
public synchronized void get()
{
while(!flag)
{
try
{
wait();
}
catch (Exception a)
{
}
}
System.out.println(Thread.currentThread().getName()+"///消费者////"+counter++);
this.notify();
flag=false;
}
}
class ShengChan implements Runnable
{
private Produse pro;
ShengChan(Produse pro)
{
this.pro=pro;
}
public void run()
{
while(true)
{
pro.set("商品");//生产
}
}
}
class XiaoFei implements Runnable
{
private Produse pro;
XiaoFei(Produse pro)
{
this.pro=pro;
}
public void run()
{
while(true)
{
pro.get();
}
}
}
class ProduseDemo
{
public static void main(String[] args)
{
Produse pro=new Produse();
ShengChan s=new ShengChan(pro);
XiaoFei x=new XiaoFei(pro);
Thread t1=new Thread(s);
Thread t2=new Thread(s);
Thread t3=new Thread(x);
Thread t4=new Thread(x);
t1.start();
t2.start();
t3.start();
t4.start();
}
毕老师讲的这个线程间通信,生产者与消费者,全部等待. 就是把if换成while,还用notify ,为什么会全部等待 弄不懂啊
|
|