我想知道在主線程中處理InterruptedException的正確方法是什麼。主線程中斷了嗎?在主線程中處理InterruptedException
我看到,join()方法拋出InterruptedException,但我想知道如何清理輔助線程才能正常終止。
這裏的示例程序:
public class Main {
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
while (true) {
if (Thread.interrupted()) {
break;
}
}
System.out.println("[thread] exiting...");
}
};
System.out.println("[main] starting the thread");
t.start();
System.out.println("[main] interrupting the secondary thread");
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
System.out.println("[main] exiting");
}
}
這段代碼將打印輸出如下:
[main] starting the thread
[main] interrupting the secondary thread
[thread] exiting...
[main] exiting
我發現在互聯網上的某些條款(如本http://www.yegor256.com/2015/10/20/interrupted-exception.html)建議將中斷標誌爲true並拋出RuntimeException。我不明白這將如何緩解這種情況(在退出前清理剩餘的線程)。
謝謝。
編輯:代碼剪斷我提到在評論
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();
Thread t = new Thread() {
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
}
System.out.println("[thread] interrupting the main thread...");
mainThread.interrupt();
System.out.println("[thread] exiting...");
}
};
System.out.println("[main] starting the thread");
t.start();
System.out.println("[main] interrupting the secondary thread");
t.interrupt();
try {
t.join();
} catch (InterruptedException e) {
System.out.println("[main] InterruptedException indeed happened");
Thread.currentThread().interrupt();
throw e;
}
System.out.println("[main] exiting");
}
}
你把你的線程包裝在任務中並使用該任務的stateProperty()。addListener – kamel2005
只要你的線程t沒有標記爲守護進程,它應該與主程序一起終止。 – kalsowerus
@ kamel2005你能解釋一下你的意思嗎?我想要實現的是主線程將停止長時間運行的輔助線程並正確處理外部中斷/信號。 – Predkambrij