Java.Multithreding.What is the difference between interrupted() and isInterrupted()?

🧠 interrupted() vs isInterrupted()

MethodStatic?Clears Interrupt Flag?Checks Which Thread?
Thread.interrupted()✅ Yes✅ Yes (resets to false)Current thread only
isInterrupted()❌ No❌ NoAny 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:

MethodBehavior
interrupted()You peek at the sign and take it down
isInterrupted()You peek at the sign, but leave it up

🧠 Summary

Featureinterrupted()isInterrupted()
Static✅ Yes❌ No
Checks current thread✅ Only❌ Must specify thread
Clears interrupt flag✅ Yes❌ No
Best forChecking + clearing in loopsMonitoring thread externally
This entry was posted in Без рубрики. Bookmark the permalink.