class ChanPin
{
private String name;
private int id=1;
private boolean flag=false;
public synchronized void set(String name)
{
while(flag)
try{wait();}catch (Exception e){}
this.name=name+"--"+id++;
System.out.println(Thread.currentThread().getName()+"我是生产者"+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
try{wait();}catch (Exception e){}
System.out.println(Thread.currentThread().getName()+"消费者"+this.name);
flag=false;
this.notifyAll();
}
}
class ShengChanZhe implements Runnable
{
private ChanPin chan;
ShengChanZhe(ChanPin chan)
{
this.chan=chan;
}
public void run()
{
while(true)
{
chan.set("chanpin");
}
}
}
class XiaoFeiZhe implements Runnable
{
private ChanPin chan;
XiaoFeiZhe(ChanPin chan)
{
this.chan=chan;
}
public void run()
{
while(true)
{
chan.out();
}
}
}
class ShengChanZheXiaoFeiZheDemo
{
public static void main(String[] args)
{
ChanPin c=new ChanPin();
ShengChanZhe sheng=new ShengChanZhe(c);
XiaoFeiZhe xiao=new XiaoFeiZhe(c);
Thread t1=new Thread(sheng);
Thread t2=new Thread(sheng);
Thread t3=new Thread(xiao);
Thread t4=new Thread(xiao);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
这是视频里毕老师打过的程序,我自己打的时候一些英文单词我就用拼音代替了
问题是在ChanPin类中 flag开始初始化如果为true的话 后面的flag的赋值也变化,
false改成true true改成false 为什么输出不了语句? |
|