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

线程问题。。。。。。。。
import   java.awt.*;
import   javax.swing.*;
import   java.awt.event.*;


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

class   thread2   extends   Thread
{
public   void   run()
{
System.out.println( "thread2 ");

}
}

public   class   threadtest
{
threadtest()
{}
public   static   void   main(String[]   args)
{
thread1   th1=new   thread1();
th1.start();
thread2   th2=new   thread2();
th2.start();
for(int   j=1;j <10;j++)
{
System.out.println( "main   thread ");
try{Thread.sleep(700);}
catch(InterruptedException   e2){}
}


}
}  

结果输出:
thread1
main   thread
thread2
thread1
main   thread
thread1
main   thread
thread1
thread1
main   thread
thread1
main   thread
thread1
main   thread
thread1
thread1
main   thread
main   thread
main   thread

为什么第二个输出的是主线程,不是thread2?

------解决方案--------------------
输出是没确定,跟CPU的时间片有关
------解决方案--------------------
楼上说的对 跟CPU的时间片有关 时间片的轮转~ 建议看一下操作系统方面的书
------解决方案--------------------
例如执行这种IO操作,CPU完全可以切换到别的线程执行。
------解决方案--------------------
在这里是三个线程(Thread1,Thread2,main)并发,所以这三个线程是随即运行的(实际上是有CPU的时间片决定的).这就是宏观并行,微观串行的道理.
------解决方案--------------------
你把循环改成10000~每次都不一样了
------解决方案--------------------
是啊
那都是随即产生的,多了就能试出来