关于这下这段代码
我实在如果SET函数和GET函数不同步的话,编译可以,运行时会报错的。
可是这俩个线程要运行的时候要读while(flag)。这个语句不是已经能保证他们俩之中只有1个线程可以继续往下运行,另一个结果为真就会执行wait线程等待吗?
为什么还需要同步这两个函数呢?
求教,下面附上代码:
class ZiYuan
{
private String name;
private int num=1;
private boolean flag=false;
synchronized void set(String a)
{
while(flag)
try{wait();}catch(Exception e ){}
this.name=a+"__"+num++;
System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
flag=true;
this.notifyAll();
}
synchronized void get()
{
while(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"消费者。。。。。。。。。"+this.name);
flag=false;
this.notifyAll();
}
}
class ZhiZao implements Runnable
{
private ZiYuan z;
ZhiZao(ZiYuan z)
{
this.z=z;
}
public void run()
{
while(true)
{
z.set("商品");
}
}
}
class XiaoShou implements Runnable
{
private ZiYuan z;
XiaoShou(ZiYuan z)
{
this.z=z;
}
public void run()
{
while(true)
{
z.get();
}
}
}
class Sorry
{
public static void main(String[] args)
{
ZiYuan z=new ZiYuan();
ZhiZao zz=new ZhiZao(z);
XiaoShou x=new XiaoShou(z);
Thread t1=new Thread(zz);
Thread t2=new Thread(zz);
Thread t3=new Thread(x);
Thread t4=new Thread(x);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|