Can't interrupt a thread if it actually computes?

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 while(true) you have something that does not throw interrupted execution (for example, a recursive function that actually evaluates something).

How do you kill this thing? And why doesn't it die?

Please note that if I do not put an Exception there and use InterruptedException , it will not even compile, saying that "interrupted exception will never be thrown" , which I do not understand why. Maybe I want to interrupt it manually ...

+7
java multithreading concurrency
source share
2 answers

I assume you mean this code segment:

 try { boolean b = true; while (true) { b = !b; } } catch(Exception e) { System.out.println("exception happened hurray!"); } 

The reason you cannot catch an InterruptedException here is because there is nothing inside this block that can throw an InterruptedException . interrupt() itself will not snatch the thread out of the loop, instead, it essentially sends a signal to the thread to tell it to stop what it is doing and do something else. If you want interrupt() break the loop, try the following:

 boolean b = true; while (true) { b = !b; // Check if we got interrupted. if(Thread.interrupted()) { break; // Break out of the loop. } } 

Now the thread checks to see if it is interrupted and exits the loop after it is completed. No try-catch .

+4
source share

Thread#interrupt more or less implemented with a flag. If a thread is blocked for some actions, ex: IO or synchronization primitives (see Javadoc), the thread is unblocked, and InterruptedException to this thread. Otherwise, a simple status flag is set to indicate that the thread was interrupted.

Your code should check this status with Thread#interrupted() or Thread#isInterrupted() (or handle InterruptedException ).

Note that checking the state with the static method clears the status.

+2
source share

All Articles