[英]Impossible to interrupt thread if its actually computing?
鑒於此代碼......
public class SimpleTest {
@Test
public void testCompletableFuture() throws Exception {
Thread thread = new Thread(SimpleTest::longOperation);
thread.start();
bearSleep(1);
thread.interrupt();
bearSleep(5);
}
public static void longOperation(){
System.out.println("started");
try {
boolean b = true;
while (true) {
b = !b;
}
}catch (Exception e){
System.out.println("exception happened hurray!");
}
System.out.println("completed");
}
private static void bearSleep(long seconds){
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {}
}
}
想象一下,而不是這個while(true)
你有一些不會拋出中斷執行的東西(例如,一個實際計算某事的遞歸函數)。
你怎么殺這個東西? 為什么它不會死?
請注意,如果我沒有在那里放置Exception
類型並使用InterruptedException
它甚至不會編譯,說"interrupted exception will never be thrown"
,我不明白為什么。 也許我想手動打斷它...
我假設你指的是這段代碼:
try {
boolean b = true;
while (true) {
b = !b;
}
} catch(Exception e) {
System.out.println("exception happened hurray!");
}
你不能在這里捕獲InterruptedException
的原因是因為該塊內部沒有任何內容可以拋出InterruptedException
。 interrupt()
本身不會將線程從循環中斷開,相反,它本質上會向線程發送一個信號,告訴它停止它正在做什么並做其他事情。 如果你想interrupt()
來打破循環,試試這個:
boolean b = true;
while (true) {
b = !b;
// Check if we got interrupted.
if(Thread.interrupted()) {
break; // Break out of the loop.
}
}
現在線程將檢查它是否被中斷,並且一旦它有中斷就退出循環。 沒有必要的try-catch
。
Thread#interrupt
或多或少用標志實現。 如果線程在某些操作上被阻止,例如:IO或同步原語(請參閱Javadoc),則線程被解除阻塞,並在該線程中拋出InterruptedException
。 否則,設置一個簡單的狀態標志,指示線程被中斷。
您的代碼需要使用Thread#interrupted()
或Thread#isInterrupted()
(或處理InterruptedException
)來檢查該狀態。
請注意,使用static
方法檢查狀態會清除狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.