What Triggers an InterruptedException
You'll learn exactly what causes a sleeping thread to wake up early and throw an InterruptedException.
The Interruption Mechanism
When you call Thread.sleep(), a thread enters the TIMED_WAITING state and pauses execution for a specified duration. But what if another thread needs to wake it up early? Java provides an interruption mechanism for this purpose.
When another thread calls .interrupt() on a sleeping thread, the sleeping thread doesn't just quietly wake up—it immediately throws an InterruptedException. This is Java's way of saying, "Hey, someone wants your attention now, not when your sleep timer expires."
How It Works
Thread worker = new Thread(() -> {
try {
System.out.println("Going to sleep...");
Thread.sleep(10000); // Sleep for 10 seconds
System.out.println("Woke up naturally");
} catch (InterruptedException e) {
System.out.println("Interrupted early!");
}
});
worker.start();
Thread.sleep(1000); // Main thread waits 1 second
worker.interrupt(); // Trigger the exception in worker thread
When worker.interrupt() executes, the worker thread immediately exits its sleep and jumps to the catch block. The sleep doesn't complete its 10 seconds—it's cut short by the interruption signal.
The Analogy
Think of Thread.sleep() like setting an alarm clock. Normally, you wake up when the alarm rings. But if someone shakes you awake before the alarm goes off, that's an interruption—an unexpected early wake-up that requires a different response.
Key Takeaway: Calling .interrupt() on a sleeping thread causes it to immediately throw InterruptedException and exit the sleep state, regardless of how much time remains.