10. public class Starter extends Thread {
11. private int x= 2;
12. public static void main(String[] args) throws Exception {
13. new Starter().makeItSo();
14. }
15. public Starter() {
16. x=5;
17. start();
18. }
19. public void makeItSo() throws Exception {
20. join();
21. x=x- 1;
22. System.out.println(x);
23. }
24. public void run() { x *= 2; }
25. }
What is the output if the main() method is rum?
A. 4
B. 5
C. 8
D. 9
E. Compilation fails.
F. An exception is thrown at runtime.
G. It is impossible to determine for certain.
Answer: D  帮我讲一下整个过程,9到底是怎么出来的呢,5*2-1得出来的???为什么呢??
     理由和原因,越详细越好。谢谢~~~顺便问一下我什么只有16分可以提供了???

解决方案 »

  1.   

    先执行new Starter()创建对象,调用构造器public Starter() { x=5;start();}这时i = 5,此时线程处于可运行状态,当cpu有时间了,就调用run()方法才是运行状态,调用public void run() { x *= 2; }后x = 10,run()方法结束后才调用makeItSo();执行join();其它线程不能执行,只有当前线程执行完了才可以。然后执行x=x- 1;此时i = 9 System.out.println(x);输出9
      

  2.   

    there are two threads, one is your class named by Starter extends Thread class, the other
    is your main method namely demon thread.
    The two threads will run with the random sequence when the application runs, but the join method make it run without random.
    The core is you must learn the join method, which implements the synchronize mechanism, e.g.
    there are two runner who are running at the same time, one is faster, but the faster wait the other when he runs the certain place untill the other runs to end, then the faster runs again.
    For this code:
    The join mothed belongs to main thread, so it must wait the Starter thread untill the Starter thread dead. So whatever the case be, the Starter thread execute the  x *= 2 sentence before the x=x- 1, because the main must wait, that is the point. so 9 is the result be here
      

  3.   


    为什么run方法在makeItSo方法之前执行呢??
    join()起到的作用是使其它线程不能执行,只有当前线程执行完了才可以执行的作用吗???
      

  4.   

    因为执行到new Starter()时,直接跳转到构造函数public Starter()去执行了,接着执行到start();时又跳转到public void run() 去执行,再才转回去执行makeItSo(),如果你一定要问为什么,这是jvm规定的顺序,至于join,它是等待该线程终止
      

  5.   

    可以先不考虑join方法,因为NEW的时候线程就执行了,执行完了才算NEW成功了,不然就会报错。
    个人看法!!!参考