鉴于此代码...
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
它甚至不会编译,说 “永远不会抛出中断的异常”
我不明白为什么。也许我想手动打断它...
最佳答案
我假设您指的是这段代码:
try {
boolean b = true;
while (true) {
b = !b;
}
} catch(Exception e) {
System.out.println("exception happened hurray!");
}
您无法在此处捕获 InterruptedException
的原因是因为该 block 内没有任何内容可以抛出 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
。
关于java - 如果它实际计算就不可能中断线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29015235/