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

java线程执行顺序的小问题
Java code

public class Ex8_2 {

    public static void main(String[] args) {
        //创建并命名每个线程
        TestThread thread1 = new TestThread("thread1");
        TestThread thread2 = new TestThread("thread2");
        TestThread thread3 = new TestThread("thread3");
System.out.println("Starting threads");
 thread1.start(); // 启动线程1
        thread2.start(); // 启动线程2
        thread3.start(); // 启动线程3
 System.out.println("Threads started, main ends\n");}  }
class TestThread extends Thread {private int sleepTime;
 public TestThread(String name)//构造函数
    { super(name);  //调用基类构造函数为线程命名
      sleepTime = (int) (Math.random()*600);//获得随机休息毫秒数
    } @Override
    public void run() //run方法是线程启动并开始运行后要执行的方法
    {
        try {
            System.out.println(
                    getName() + " going to sleep for " + sleepTime);

            Thread.sleep(sleepTime); //线程休眠
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
        System.out.println(getName() + " finished");//运行结束,给出提示信息
    }
}


运行结果:Starting threads
Threads started, main ends


thread3 finished
thread2 finished
thread1 finished



因为是随机产生睡眠时间的,所以结果会有所不同。
问题:
虽然是随机产生睡眠时间的但是我觉得应该有个顺序的,应该是睡眠时间较短的先执行,但是为什么会thread3 最后打印啊?
我觉得顺序应该为thread3 going to sleep for 473
thread2 going to sleep for 459
thread1 going to sleep for 210


不懂!

------解决方案--------------------
http://topic.csdn.net/u/20110621/16/d576fcd8-8ce4-47ba-bf5d-b8435d2a674d.html
------解决方案--------------------
线程的第一个打印语句,执行顺序是随机的。(有时候主线程还没结束,已经输出了第一个打印语句)
线程得第二个打印语句,和sleepTime有关,sleepTime越大,结束的越晚。
------解决方案--------------------
该结贴了。