Question 122
Given: 
1. public class TestOne implements Runnable { 
2. public static void main (String[] args) throws Exception { 
3. Thread t = new Thread(new TestOne()); 
4. t.start(); 
5. System.out.print(“Started”)
6. t.join();
7. System.out.print(“Complete”)
8. } 
9. public void run() { 
10. for (int i= 0; i< 4; i++) { 
11. System.out.print(i); 
12. } 
13. } 
14. } 
What can be a result? 
A. Compilation fails. 
B. An exception is thrown at runtime. 
C. The code executes and prints “StartedComplete”
D. The code executes and prints “StartedComplete0123”
E. The code executes and prints “Started0l23Complete”
Answer: E
这是什么原理啊??????????
我认为的是t.start()调用run()之后,应先运行run()的方法中定义的操作,也就是先输出:0123,然后再输出Started和Complete.我想答案应该就是: 0123StartedComplete.可为什么是E????谢谢...

解决方案 »

  1.   

    t.start()后,线程开始执行,而主线程继续执行...应该先执行System.out...输出Start,(因为调用线程后,再进入run再执行循环语句要好几步呢,而主线程继续执行System....这条语句一步就行了),之后join主线程让出,等线程执行完,主线程继续执行.
      

  2.   

    调用t.start(); 只是告诉系统,这个t线程已经准备就绪了,处于就绪状态,并没有把它的优先级提高最高,它后面的System.out.print(“Started”) 
    还会继续执行的,这就要看系统怎么分配cpu了。
    考虑到下面的语句(标红色)
    t.join(); 
    System.out.print(“Complete”) 

    所以System.out.print(“Complete”) 肯定在run执行完以后才能执行
      

  3.   

    我想蛋炒饭的意思是:一,有个调用main的主线程,二.有个程序中自己定义的相对于主线程的小线程t.
    这个join是由t来调用的啊,怎么会使主线程让出呢 ??t.join(),不就是让自己定义的线程t    Waits for this thread to die  吗?
      

  4.   

    线程优先级的问题吧..如上所说..main线程应该是个高优先级线程
      

  5.   

    很正常啊,他一直没主线程;
     Thread t = new Thread(new TestOne());
     t.start();//启动负线程,运行run方法;
     System.out.println("Started");
                     //主线程输出,这句与Thread t = new Thread(new TestOne())是同组的,所以他比较快一点;
     t.join();//负线程等待
     System.out.print("Complete");
      

  6.   

    我看API说明时,有下面这段话:
    join
    public final void join()
                    throws InterruptedException
    Waits for this thread to die. //请问是谁waits for this thread to die啊?这个谁也是个thread吗?Throws: 
    InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
      

  7.   

    t.join(); 这句就是告诉当前线程(main)要想继续执行的话,那就必须等t线程执行完毕后才行。
      

  8.   

    t.join()可以理解为将t加入正在运行的线程