多线程里的if问题,在inPut类中,那个加注释的else不去掉运行结果就错误,毕老师就没写else,有无else有区别吗,
class Res
{
boolean flag=false;
String name;
String sex;
}
class inPut implements Runnable
{
int x=0;
Res r;
inPut(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
synchronized(r)
{
if(r.flag)
{
try
{
r.wait();
}
catch (Exception e)
{
}
}
else//去掉else就没事了
if (x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex="女...";
}
r.flag=true;
r.notify();
}
x=(x+1)%2;
}
}
}
class outPut implements Runnable
{
Res r;
outPut(Res r)
{
this.r=r;
}
public void run()
{
while (true)
{
synchronized(r)
{
if (!r.flag)
try
{
r.wait();
}
catch (Exception e)
{
}
else
{
System.out.println(r.name+r.sex);
r.flag=false;
r.notify();
}
}
}
}
}
class lianxi
{
public static void main(String[] args)
{
Res r = new Res();
inPut in =new inPut(r);
outPut out = new outPut(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
|