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?

解决方案 »

  1.   

    输出是没确定,跟CPU的时间片有关
      

  2.   

    楼上说的对 跟CPU的时间片有关 时间片的轮转~ 建议看一下操作系统方面的书
      

  3.   

    都说了跟CPU的时间片轮转有关 你查看一下 操作系统 方面的书籍 看一下时间片的轮转你就知道了 CPU对待线程并不是一视同仁的 就像你上面写的那个程序 CPU有时候偏向main thread(给他的时间片较长) 有时偏向thread1(同理) 有时一样 就是不规则的 所以有时输出main thread
    多一点 有时输出thread1多一点 有时还交替
      

  4.   

    例如执行这种IO操作,CPU完全可以切换到别的线程执行。
      

  5.   

    在这里是三个线程(Thread1,Thread2,main)并发,所以这三个线程是随即运行的(实际上是有CPU的时间片决定的).这就是宏观并行,微观串行的道理.