2016-05-12 46 views
1

我們知道我們可以通過創建一個新的類來擴展線程,然後創建該線程的一個實例來創建一個新線程。通過此主題,我看到一個示例我的書如下。通過擴展線程類創建一個線程時出現混亂

class NewThread extends Thread{ 
    NewThread(){ 
     super("demo thread"); 
     System.out.println("child thread:"+this); 
     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"); 
     } 
    } 
在這個例子中,我能夠明白,只是在我們沒有使用任何實例(線程)調用start()構造部分的所有這些事情

。所以我的問題是start()方法是如何沒有任何線程調用。

+0

如果你不明白爲什麼'開始()'調用在你的構造函數中不需要明確的對象引用,那麼你可能會更好地利用你的時間瞭解更多關於Java語言在嘗試理解Java線程之前的年齡。 –

回答

0

它是有效的,因爲方法start()繼承自Thread類,因此您可以像調用任何其他類方法一樣調用它。

0

此start()方法在線程實例上調用,該實例剛剛在此構造函數中創建。

1

您正在繼承NewThread類擴展的類Thread的start()方法。所以你可以像其他方法一樣調用它。

run()方法也可以使用@Override註解,以使繼承的概念更加清晰。

@Override 
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"); 
    } 
0

下面的代碼負責調用start()方法您NewThread比如在NewThread構造函數,調用start()方法Thread類,它調用run()方法。

NewThread(){ 
    super("demo thread"); 
    System.out.println("child thread:"+this); 
    start(); 
} 

流量:

NewThread() -> start() -> Thread start() -> native start0() -> run() 

請參閱本SE問題的Threadstart()方法的內部:

What's the difference between Thread start() and Runnable run()