本帖最后由 邹海洋 于 2012-10-30 13:19 编辑
这个程序跟老师的几乎一模一样,但是编译失败,求解?
/*
线程间通信存在的问题
int 和 out 不同步
有一堆资源
两辆车,一进 一出
两条路
*/
class ZiYuan
{
String name;
String sex;
boolean flag = false ;
}
class InPut implements Runnable
{
ZiYuan zy;
InPut(ZiYuan zy)
{
this.zy = zy;
}
public void run()
{
int x = 0;
while (true)
{
synchronized(zy)
{
if (ZiYuan.flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}
if (x==0)
{
zy.name = "mike";
zy.sex = "man";
}
else
{
zy.name = "丽丽";
zy.sex = "女";
}
ZiYuan.flag = true;
notify();
}
x = (x+1)%2;
}
}
}
class OutPut implements Runnable
{
ZiYuan zy ;
OutPut(ZiYuan zy)
{
this.zy = zy;
}
public void run()
{
while (true)
{
synchronized(zy)
{
if (!ZiYuan.flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}
System.out.println(zy.name+"....."+zy.sex);
ZiYuan.flag = false;
notify();
}
}
}
}
class InOutDemo
{
public static void main(String[] args)
{
ZiYuan zy = new ZiYuan();
InPut in = new InPut(zy);
OutPut out = new OutPut(zy);
Thread t1 = new Thread(in);
Thread t2= new Thread(out);
t1.start();
t2.start();
}
}
|