public class BadThreads {    static String message;    private static class CorrectorThread
        extends Thread {        public void run() {
            try {
                sleep(3000); 
            } catch (InterruptedException e) {}
            // Key statement 1:
            message = "Mares do eat oats."; 
        }
    }    public static void main(String args[])
        throws InterruptedException {
        (new CorrectorThread()).start();
        message = "Mares do not eat oats.";
        Thread.sleep(4000);
        // Key statement 2:
        System.out.println(message);
    }
}
请问这段代码执行的顺序是怎样的?执行结果呢?

解决方案 »

  1.   

    汗了...这个你运行一下不就知道了嘛...
    想知道自己的运行顺序 加几个打印语句就是了
    另外,线程执行情况不可控,单机运行执行情况不能作为共性,线程的启动和执行由CPU负责控制
    public class Test {
    static String message;
     private static class CorrectorThread
         extends Thread {     public void run() {
          System.out.println("thread init success");
             try {
                 sleep(3000);
                 System.out.println("thread thread_sleep success");
             } catch (InterruptedException e) {}
             // Key statement 1:
             message = "Mares do eat oats.";
             System.out.println("thread set message success set to -> Mares do eat oats.");
          }
     }
    public static void main(String[] args) throws InterruptedException {
    System.out.println("now is started");
    (new CorrectorThread()).start();
    System.out.println("thread is registered");
            message = "Mares do not eat oats.";
            System.out.println("main function set message success set to -> Mares do not eat oats.");
            Thread.sleep(4000);
            System.out.println("main function thread_sleep success");
            // Key statement 2:
            System.out.println(message);
    }
    }我的执行结果:
    now is started
    thread is registered
    main function set message success set to -> Mares do not eat oats.
    thread init success
    thread thread_sleep success
    thread set message success set to -> Mares do eat oats.
    main function thread_sleep success
    Mares do eat oats.
      

  2.   

    不同意楼上观点;
    启动顺序肯定是先是主线程,就是main函数所在的线程,然后是在main函数中启动的另一个线程new CorrectorThread()).start();
    在第二个线程启动之后,两个线程并行执行。所以语句执行的先后有随机性。这个随机性与睡眠的时间有关,时间相差越短,随机性越高。所以执行的结果可能是eat也可能是don't eat。但是在特定的环境下,比如楼主的主机环境下,睡眠3000和4000,可能尝试100次结果都是相同的,但是这不足以证明,这个执行顺序就是确定的,在其他环境下(比如把睡眠时间改为20),不一定这个结果。
      

  3.   

    我说的是线程的执行情况不确定,没说错吧?
    以这个程序来说,一个等待3秒一个等待4秒,是不太可能碰到打印dont的情况,但是我想LZ的意思也肯定研究是两个线程的关系吧,如果你把main的改成Thread.sleep(3010)哪?
    或者假设,LZ的CPU就是20年前的产品,启动线程时间就是超过1秒以上哪?
      

  4.   

    那怎样修改,能保证每次执行完程序打印:Mares do eat oats。