黑马程序员技术交流社区

标题: 线程代码打印出现null? [打印本页]

作者: 张玉建    时间: 2012-4-25 19:08
标题: 线程代码打印出现null?
class res
{
String name ;
String sex;

}
class input implements Runnable
{
private res r;
input(res r)
{
  this.r = r ;
}
public void run()
{
  int x=0;
  while(true)
  {
   synchronized(r)
   {
   
    if (x==0)
    {
     r.name="zhang ";
     r.sex="man";
    }
    else
    {
     r.name="丽丽";
     r.sex="女";
    }
    x=(x+1)%2;
   
   }
   
  }
}
}
class output implements Runnable
{
private res r;
output(res r)
{
  this.r = r ;
}
public void run()
{
  while(true)
  {
   synchronized(r)
   {
   
    System.out.println(r.name+"...."+r.sex);
   
   }
  }
   
}
}


class  inputoutputdome
{
public static void main(String[] args)
{
  res r =new res();
  input in = new input(r);
  output ou = new output(r);
  Thread t1 =new Thread(in);
  Thread t2 =new Thread(ou);
  t1.start();
  t2.start();
}
}
打印出现     null...null后后面就正常了!
代码中还有问题!求解?

作者: 张小庆    时间: 2012-4-25 19:20
运行了一下 没问题啊  挺正常的啊

作者: 张玉建    时间: 2012-4-25 19:44
我运行时1首先出现null...null  
后就正常了!我就郁闷了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2