Checking and Clearing: Thread.interrupted()
What you'll learn: How the static Thread.interrupted() method both checks and automatically clears the current thread's interruption flag in a single operation.
The Core Difference
You've already learned isInterrupted(), which checks a thread's interruption status without changing it. Now meet its cousin: Thread.interrupted().
This static method does two things atomically:
- Checks if the current thread is interrupted
- Clears the interruption flag (resets it to
false)
Think of it like a smoke detector with a test-and-reset button. Pressing it tells you if smoke was detected and immediately resets the alarm state—all in one action.
When to Use It
Use Thread.interrupted() when you want to acknowledge and handle an interruption, then continue normal operation:
public void processItems() {
while (true) {
if (Thread.interrupted()) {
// Interruption detected AND cleared
System.out.println("Interrupted, cleaning up...");
cleanup();
return; // Exit gracefully
}
// Continue processing
doWork();
}
}
Critical Distinction
someThread.isInterrupted(): Checks that specific thread, leaves flag unchangedThread.interrupted(): Checks current thread, clears the flag
The clearing behavior is crucial. If you check again immediately:
boolean first = Thread.interrupted(); // true, then cleared
boolean second = Thread.interrupted(); // false (flag was cleared)
Why Clear Automatically?
This design allows a thread to detect it's been interrupted, handle the situation appropriately, and then resume work without the interruption flag "stuck" in the set state. It's a consume-once notification pattern.
Key Takeaway: Thread.interrupted() is a static method that checks the current thread's interruption status and immediately clears it—use it when you want to detect and consume an interruption signal in one atomic operation.