🧠 interrupted()
vs isInterrupted()
Method | Static? | Clears Interrupt Flag? | Checks Which Thread? |
---|---|---|---|
Thread.interrupted() | ✅ Yes | ✅ Yes (resets to false) | Current thread only |
isInterrupted() | ❌ No | ❌ No | Any specific thread object |
✅ Thread.interrupted()
- Static method
- Checks the interrupted status of the current thread
- Clears the flag after checking (resets it to
false
)
Example:
Thread.currentThread().interrupt(); // Set the interrupt flag
System.out.println(Thread.interrupted()); // true (and resets the flag)
System.out.println(Thread.interrupted()); // false (already cleared)
Use this if you’re inside a thread and want to check and clear the flag in one go.
✅ isInterrupted()
- Instance method
- Checks the interrupt status of a specific thread
- Does not clear the flag
Example:
Thread t = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// do work
}
System.out.println("Thread interrupted!");
});
t.start();
Thread.sleep(1000);
t.interrupt(); // Sets interrupt flag
System.out.println(t.isInterrupted()); // true
Use this if you want to monitor or log whether a thread was interrupted — without affecting its flag.
🔁 Real-World Analogy
Think of the interrupt flag like a “Do Not Disturb” sign:
Method | Behavior |
---|---|
interrupted() | You peek at the sign and take it down |
isInterrupted() | You peek at the sign, but leave it up |
🧠 Summary
Feature | interrupted() | isInterrupted() |
---|---|---|
Static | ✅ Yes | ❌ No |
Checks current thread | ✅ Only | ❌ Must specify thread |
Clears interrupt flag | ✅ Yes | ❌ No |
Best for | Checking + clearing in loops | Monitoring thread externally |