class Resource{
String name;
String sex;
}
class Input implements Runnable{
Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r)
{
if(x==0)
{
r.name
="gejia";
r.sex="nan";
}
else
{
r.name
="晓丽";
r.sex="女生女生";
}
}
x=(x+1)%2;
}
}
}
class Output implements Runnable{
Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
System.out.println(r.name
+"..."+r.sex);
}
}
}
}
class Myjava{
public static void main(String[] arg){
Resource r=new Resource();
Output out=new Output(r);
Input in=new Input(r);
Thread t1=new Thread(out);
Thread t2=new Thread(in);
t1.start();
t2.start();
}
}
为什么output类的run方法要加同步?×input类run()已经加了同步,别的线程无法进入,为什么到输出的时候就出问题?