vac*_*ach 7 java concurrency multithreading
鉴于此代码......
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) {}
}
}
Run Code Online (Sandbox Code Playgroud)
想象一下,不是这样,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!");
}
Run Code Online (Sandbox Code Playgroud)
您无法在此处捕获 的原因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.
}
}
Run Code Online (Sandbox Code Playgroud)
现在线程将检查它是否被中断,并在中断后跳出循环。没有try-catch必要。