Interrupt a Sleeping Thread in Java
Problem
Interrupting a thread sets a flag on it; blocking calls such as sleep, wait and join respond by throwing InterruptedException.
Start a thread that sleeps for 10 seconds, then wake it after 200 milliseconds from the main thread.
Java Program
public class InterruptThreadExample {
public static void main(String[] args) throws InterruptedException {
Thread sleeper = new Thread(() -> {
try {
Thread.sleep(10_000); // would sleep for 10 seconds
System.out.println("Woke up normally");
} catch (InterruptedException e) {
System.out.println("Interrupted while sleeping, cleaning up");
}
});
sleeper.start();
Thread.sleep(200);
sleeper.interrupt(); // wakes it up early with an InterruptedException
sleeper.join();
System.out.println("Main: sleeper finished, alive = " + sleeper.isAlive());
}
}Output
Core Logic
interrupt() doesn't kill a thread — it asks it to stop, and a sleeping thread receives that request as an exception.
- 1The sleeper calls
Thread.sleep(10_000)inside a try block. - 2Main waits 200 ms, then calls
sleeper.interrupt(). - 3The sleep ends immediately with
InterruptedException, and the catch block cleans up. - 4Main joins the sleeper and confirms it has finished.
Key Point: Never swallow InterruptedException silently — either finish the task, or restore the flag with Thread.currentThread().interrupt() so callers can see it.
Key Concepts
Approach 2: Checking the Interrupt Flag in a Loop
public class InterruptLoopCheck {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) { // a polite worker checks its flag
Thread.onSpinWait(); // stands in for one unit of real work
}
System.out.println("Worker noticed the interrupt flag and stopped");
});
worker.start();
Thread.sleep(100);
worker.interrupt(); // just sets the flag; the worker decides how to stop
worker.join(2000);
System.out.println("Worker alive: " + worker.isAlive());
}
}
Output
Core Logic
A thread that's busy computing never throws InterruptedException, so it has to check its own interrupt flag.
- 1The worker loops while
Thread.currentThread().isInterrupted()is false. - 2Main calls
worker.interrupt(), which sets the flag. - 3The worker sees the flag on its next check and exits.
isAlive() is then false.Key Point: Thread.interrupted() also checks the flag but clears it, while isInterrupted() leaves it set.
Key Concepts
Interview Questions
What does catching InterruptedException do to the flag?
Throwing it clears the interrupt flag. That's why the standard advice is to re-interrupt with Thread.currentThread().interrupt() if you can't handle it fully.
How does an ExecutorService cancel running tasks?
shutdownNow() and future.cancel(true) interrupt the worker threads, so tasks must respond to interruption to stop promptly.