class shen implements Runnable
{
xuni xu;
public shen(xuni xu)
{
this.xu=xu;
}
public void run()
{
  int x=0;
while(true)
{
  synchronized(xu)
  {
   try
   {
   if(xu.bfull)
   {
   xu.wait();
   }
   }
   catch(Exception ex)
   {
  
   }
if(x==0)
{
xu.name="lizhao";
//try{Thread.sleep(1);}catch(Exception ex){}
xu.sex="man";
}
else
{
xu.name="xingyu";
xu.sex="male";
}
xu.bfull=true;
xu.notify();
}
x=(x+1)%2;
}
}
}
class xiao implements Runnable
{
xuni xu;
public xiao(xuni xu)
{
this.xu=xu;
}
public void run()
{
while(true)
{
    synchronized(xu)
    {
     try
     {
     if(!xu.bfull)
     {
     xu.wait();
     }
     }
catch(Exception ex)
{

}
System.out.print(xu.name+":");
  System.out.println(xu.sex);
  xu.bfull=false;
  xu.notify();
  }
}
}
}
class xuni
{
String name="no";
String sex="no";
boolean bfull=false;
}
class zhu
{
public static void main(String[] args)
{
xuni xu2=new xuni();
new Thread(new shen(xu2)).start();
new Thread(new xiao(xu2)).start();
}
}以上的程序是先运行的哪个线程?
shen类中run()方法中
if(xu.bfull)括号中的xu.bfull值是true还是false呀?xiao类中run()方法中
if(!xu.bfull)括号中的xu.bfull值是true还是false呀?程序的运行顺序是怎么样的呀?谁能给解读一下.

解决方案 »

  1.   

    shen类中run()方法中 
    if(xu.bfull)括号中的xu.bfull值是true还是false呀? //falsexiao类中run()方法中 
    if(!xu.bfull)括号中的xu.bfull值是true还是false呀?  //true
    对于这个问题,要看你在xuni类中的bfull初始化值,多线程的运行顺序跟CPU的性能有关.不同的
    机器运行同一个程序,会有不同的结果.
      

  2.   

    以上的程序是先运行的哪个线程? 
    先执行new Thread(new shen(xu2))shen类中run()方法中 
    if(xu.bfull)括号中的xu.bfull值是true还是false呀? //false
    xiao类中run()方法中 
    if(!xu.bfull)括号中的xu.bfull值是true还是false呀? //false故!xu.bfull为true.程序的运行顺序是怎么样的呀?谁能给解读一下.
    该程序就没有实现同步,同步关键字synchronized在不同的类中。