想了一个晚上都不明白,按照以下代码为什么会重复打印man或者重复打印女女女女女女,按理说不是轮流打印吗,求解析,万分感激
class InperOurperDemo
{
public static void main(String[] args)
{
Res r = new Res();
Thread t1 = new Thread(new Inper(r));
Thread t2 = new Thread(new Ourper(r));
t1.start();
t2.start();
}
}
class Res
{
String name;
String sex;
boolean flag;
}
class Inper implements Runnable
{
private Res r;
Inper(Res r)
{
this.r = r;
}
public void run()
{
int x=0;
while(true)
{
if (r.flag)
{
try{r.wait();} catch(Exception e){}
}
synchronized(r)
{
if (x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name= "丽丽";
r.sex= "女女女女女女";
}
x=(x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
class Ourper implements Runnable
{
private Res r;
Ourper(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
if(!r.flag)
{
try{r.wait();}catch(Exception e){}
}
synchronized(r)
{
System.out.println(r.name+"........"+r.sex);
r.flag = false;
r.notify();
}
}
}
} |