2015-07-12 69 views
0

我是從完全參考閱讀多線程,然後我感到震驚這段代碼,我無法理解這code.Can某人的輸出幫助我?查詢有關Java線程

class NewThread implements Runnable 
{ 
    Thread t; 
    NewThread() 
    { 
     t = new Thread(this, "Demo Thread"); 
     System.out.println("Child thread: " + t); 
     t.start(); 
    } 
    public void run() 
    { 
     try 
     { 
      for(int i = 5; i > 0; i--) 
      { 
       System.out.println("Child Thread: " + i); 
       Thread.sleep(500); 
      } 
     } 
     catch (InterruptedException e) 
     { 
      System.out.println("Child interrupted."); 
     } 
     System.out.println("Exiting child thread."); 
    } 
} 
class First 
{ 
    public static void main(String args[]) 
    { 
     new NewThread(); 
     try 
     { 
      for(int i = 5; i > 0; i--) 
      { 
       System.out.println("Main Thread: " + i); 
       Thread.sleep(1000); 
      } 
     } 
     catch (InterruptedException e) 
     { 
      System.out.println("Main thread interrupted."); 
     } 
     System.out.println("Main thread exiting."); 
    } 
} 

它產生的輸出:

子線程:螺紋[演示螺紋,如圖5所示,主]

主線:5

子線程:5

Child Thread:4

Main主題:4

子線程:3

子線程:2

主線:3

子線程:1

退出子線程

主線:2

主線程:1

主線程退出

從main()方法中,NewThread()調用構造函數,然後Thread類的一個實例被創建名爲「演示線」和第一次印刷()語句被執行然後start()方法被調用。這個start方法不應該隱式地調用run()方法,所以應該執行子循環,但是根據輸出控制進入主循環。如何控制去main()循環,即使我們調用t.start()?有人可以向我澄清一下代碼輸出嗎?

+1

請注意,這使用非標準間距標準,難以閱讀;這種佈局(尤其是將開口花括號放在他們自己的路線上)並不能模仿。 – chrylis

+0

@ chrylis-Is現在好嗎? –

+0

線程的要點是讓事情執行*併發*。啓動一個線程執行run()方法,在* another *線程中,它並行*執行到主線程。主線程不會等待新線程完成,否則,啓動線程將毫無用處。 –

回答

1

除非有發生之間的關係,獨立線程的執行順序是非確定性的;這是什麼讓併發具有挑戰性。在調用t.start()之後,主線程和t中的線程之間完全沒有關係,並且在系統負載很重的情況下,一個線程或另一個線程理論上可以在控制返回到其他線程之前完成所有的順序在所有。

3

一旦start()被調用,現在有兩個線程同時運行。 start()立即返回並且主循環繼續(一個循環非常1000mS)。但兒童循環現在也在同一時間運行 - 每500mS一個循環。因此,直到每個循環結束,都會爲每條主線打印兩條子線。