[英]confusion while creating a thread by extending thread class
我們知道我們可以通過創建一個擴展線程的新類來創建一個新線程,然后創建該線程的一個實例..在閱讀這個主題時,我在我的書中看到了一個例子,如下所示。
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() 方法。
您正在從 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");
}
它是有效的,因為方法start()
繼承自Thread
類,因此您可以像調用任何其他類方法一樣調用它。
這個 start() 方法是在線程實例上調用的,線程實例剛剛在這個構造函數中創建。
下面的代碼負責調用start()
方法在你NewThread
的情況下NewThread
構造函數,它調用start()
方法Thread
類,它調用run()
方法。
NewThread(){
super("demo thread");
System.out.println("child thread:"+this);
start();
}
流動:
NewThread() -> start() -> Thread start() -> native start0() -> run()
有關Thread
類start()
方法的內部結構,請參閱此 SE 問題:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.