首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

一个线程的有关问题

2012-01-29 
求助一个线程的问题先读一读这样一段程序:publicclassExample{publicstaticvoidmain(Stringargs[]){Leftha

求助一个线程的问题
先读一读这样一段程序:
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的还没运行完。

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

热点排行
Bad Request.