日期:2014-05-20  浏览次数:20652 次

求助一个线程的问题
先读一读这样一段程序:
public   class   Example
{
    public   static   void   main(String   args[])
    {
          Lefthand   left;
          Righthand   right;
          left=new   Lefthand();
          right=new   Righthand();
          left.start();
          right.start();
    }
}

class   Lefthand   extends   Thread
{
    public   void   run()
    {
          for   (int   i=1;i <=5;i++)
          {
              System.out.print( "A ");
              try
              {
                  sleep(500);
              }
              catch(InterruptedException   e)
              {
              }
          }
    }
}

class   Righthand   extends   Thread
{
    public   void   run()
    {
          for   (int   i=1;i <=5;i++)
          {
              System.out.print( "B ");
              try
              {
                  sleep(300);
              }
              catch(InterruptedException   e)
              {
              }
          }
    }
}

上面程序的打印结果是ABBABBABAA

现在的问题是当程序经过了1500毫秒的时候为什么打印结果是两个A,也就是上述打印结果末尾的两个A?

------解决方案--------------------
最后两个AA是因为:Righthand的五次B已经全问打印完了,只有A的还没运行完。

这只是单核的时候,要是并行的结果就不一定了。
------解决方案--------------------
这样的结果是非常随机的!这和缓冲区有关系。其实深究这样的代码无义,因为是随机的。