[英]Behavior of thread by extending Thread class
我有以下class
:
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("I am the first thread");
}
public static void main(String args[]) {
Thread1 t = new Thread1();
t.start();
}
}
如果我運行上面的程序,它將在新線程中打印
"I am the first thread"
現在在 main 中,如果我嘗試啟動同一個線程兩次,它將拋出java.lang.IllegalThreadStateException
現在我將通過覆蓋start()
方法重寫 Thread1 類,如下所示
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("I am the first thread");
}
@Override
public void start() {
System.out.println("I am the Start");
}
public static void main(String args[]) {
Thread1 t = new Thread1();
t.start();
t.start();
}
}
現在,如果我調用start()
方法兩次,輸出將是:
I am in start
I am in start
上面的程序拋出任何異常。 誰能解釋我這種行為。 為什么它不啟動新線程。 看似簡單,卻看不懂。
當@Override
一個方法時,您正在創建的新方法將被調用而不是之前的方法。
在Thread
類中, start()
是一種執行某些操作並啟動 Thread 的方法。
在你的新類Thread1
, start()
是一個只打印一行Thread1
做其他事情的方法
您的理解是正確的 - 調用super.start()
是調用超類的start()
版本,它允許線程實際開始運行。
但請注意,當您嘗試運行它兩次時仍然會遇到該異常。 這就是Thread
的設計方式。
來自問題評論中的鏈接:
多次啟動一個線程是不合法的。 特別是,線程一旦完成執行就可能不會重新啟動。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.