[英]IllegalThreadStateException on Thread.interrupt
我有一個Java程序,需要很長時間才能編譯。
出於測試目的,如果編譯需要很長時間,我想終止程序並重新啟動它。
這是我的代碼的簡化版本:
public class Main {
public static void main(String[] args) {
Thread foo = new Thread(new Foo());
while (true) {
foo.start();
while (true) {
if (needRestart()) {
foo.interrupt();
break;
}
}
}
}
}
foo.java看起來像這樣:
public class Foo implements Runnable {
// some code
public void run () {
try {
while (!Thread.currentThread().isInterrupted()) {
// some code
}
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
問題是程序崩潰並拋出IllegalThreadStateException
如果您需要完整的代碼,則為: 完整的代碼
不要在while(true)
循環中啟動foo線程。 您只能在一個生命周期中啟動一個Thread
。
移動foo.start();
以上while(true)
有關線程類start()
方法的信息,請參考oracle文檔頁面
public void start()
使該線程開始執行; Java虛擬機將調用此線程的run方法。
結果是兩個線程同時運行:當前線程(從調用返回到start方法)和另一個線程(執行其run方法)。
一次啟動一個線程永遠是不合法的。 特別是,線程一旦完成執行就可能不會重新啟動。
IllegalThreadStateException
當您試圖改變你的線程的狀態或當您嘗試再次調用同一個線程start方法,一旦它處於運行狀態發生。 但是在您的情況下,如果您想中斷線程,請使其進入sleep()
,並希望在該線程自動退出睡眠之前中斷對該線程的調用notify()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.