Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 1 decade ago

搞不懂的Thread 的 問題

class A implements Runnable { public void run() {System.out.print(Thread.currentThread().getName());}}class B implements Runnable { public void run() { new A().run(); new Thread(new A(),"T2").run(); new Thread(new A(),"T3").start(); }}class C { public static void main (String[] args) { new Thread(new B(),"T1").start(); }}

What is the result of attempting to compile and run the program?

為何答案是Prints: T1T1T3 呢?

可以講詳細一點的流程嗎? Q_Q

1 Answer

Rating
  • Anonymous
    1 decade ago
    Favorite Answer

    class A implements Runnable {

    public void run() {

    System.out.print(Thread.currentThread().getName());}

    }

    class B implements Runnable {

    public void run() {

    new A().run();

    new Thread(new A(),"T2").run();

    new Thread(new A(),"T3").start();

    }

    }

    class C {

    public static void main (String[] args) {

    new Thread(new B(),"T1").start();

    }

    }

    ---------------------------------------------------------

    首先,在main,程式產生名為T1的執行緒 ,並執行 Class B run()函式中的程式碼。

    因為 new Thread(....).run() 並不會產生執行緒,仍會由T1執行。

    new A().run();

    new Thread(new A(),"T2").run();

    因為這兩行程式碼由T1執行,所以會print T1T1。

    到 new Thread(new A(),"T3").start(); 程式會產生名為T3的執行緒,所以Class A的run()會print T3。

    因此答案是 T1T1T3

    請注意執行Thread的run()並不會改變執行緒的狀態。(注:參考資料)

Still have questions? Get your answers by asking now.