class Sources
{
String name;
String sex;
}
class inPut implements Runnable
{
Sources s;
inPut(Sources s)
{
this.s=s;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
{
this.s.name="三公子";
this.s.sex="男";
}
else
{
this.s.name="三公主";
this.s.sex="女";
}
x++;
x=x%2;
}
}
}
class outPut implements Runnable
{
Sources s;
outPut(Sources s)
{
this.s=s;
}
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+" "+s.name+" "+s.sex);
}
}
}
class Name
{
public static void main(String[] args)
{
Sources s=new Sources();
inPut in=new inPut(s);
outPut out=new outPut(s);
Thread td1=new Thread(in);
Thread td2=new Thread(out);
td1.start();
td2.start();
System.out.println("Hello World!");
}
}
{
String name;
String sex;
}
class inPut implements Runnable
{
Sources s;
inPut(Sources s)
{
this.s=s;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
{
this.s.name="三公子";
this.s.sex="男";
}
else
{
this.s.name="三公主";
this.s.sex="女";
}
x++;
x=x%2;
}
}
}
class outPut implements Runnable
{
Sources s;
outPut(Sources s)
{
this.s=s;
}
public void run()
{
while(true)
{
System.out.println(Thread.currentThread().getName()+" "+s.name+" "+s.sex);
}
}
}
class Name
{
public static void main(String[] args)
{
Sources s=new Sources();
inPut in=new inPut(s);
outPut out=new outPut(s);
Thread td1=new Thread(in);
Thread td2=new Thread(out);
td1.start();
td2.start();
System.out.println("Hello World!");
}
}
分析:出现这种的情况的原因?
答:
当 this.s.name="三公子";
this.s.sex="男";这句的时候突然切换到了其他线程执行 this.s.name="三公主";,所以当输出的时候就出现了这样的情况.