本帖最后由 征服 于 2014-4-3 08:59 编辑
synchronized(obj),为什么结果出错了呢?求助!谢谢!
class Res
{
String name;
String sex;
}
class Input implements Runnable
{
Object obj=new Object();
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(obj)
{
if(x==0)
{
r.name="迈克";
r.sex="男";
}
else
{
r.name="丽丽";
r.sex="女";
}
x=(++x)%2;
}
}
}
}
class Output implements Runnable
{
Object obj=new Object();
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(obj)
{
System.out.println("name="+r.name+"...."+"sex="+r.sex);
}
}
}
}
class InputOutputDemo
{
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();
}
}
|