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

求问个简单的线程问题
非常初级,废话不多说,上源码:


public class Test {

?? ?public static void main(String[] args) {
?? ? ? ?
?? ? ? ?MyRun my = new MyRun();
?? ? ? ?Thread td = new Thread(my);
?? ? ? ?
?? ? ? ?td.start();
?? ? ? ?System.out.println("this is from main");
?? ?}
}


class MyRun implements Runnable{

?? ?@Override
?? ?public void run() {
?? ? ? ?System.out.println("this is from myrun"); ? ?
?? ?}
?? ?
}

=========================================
执行结果:
this is from main
this is from myrun

问题是,明明td.start()在先,为什么不先执行,为什么不是下面的结果:
this is from myrun
this is from main

拜谢!!!!

------解决方案--------------------
这就是两个线程main函数本身是一个线程,你new出来了一个线程,至于谁先执行,是没有顺序可言的,如果你在 System.out.println("this is from main");语句之前sleep几秒,就会先打印this is from myrun了。。。。
------解决方案--------------------
主线程抛线程出去后准备执行run方法需要花一些时间,主线程抛出线程后直接运行后面的代码,所以主线程先输出