Given this code...
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) {}
}
}
Imagine that instead of this while(true)
you have something that does not throw interrupted execution (for example, a recursive function that actually calculates something).
How do you kill this thing? And why is it not dying?
Note if I don't put Exception
type there and use InterruptedException
it won't even compile, saying that "interrupted exception will never be thrown"
which I don't understand why. Maybe I want to interrupt it manually...