Difference Interrupted and Isinterrupted
In Java, both interrupted() and isInterrupted() methods are used to check the interrupt status of a thread, but they differ in their behavior regarding how they interact with the interrupted status flag.
Table of Contents
Here’s the difference between interrupted() and isInterrupted():
1. interrupted():
This method is a static method of the Thread class. It not only checks whether the current thread has been interrupted but also clears the interrupted status flag. If the interrupted status flag was set before calling interrupted(), it returns true, indicating that the thread was interrupted. However, after calling interrupted(), regardless of whether the thread was interrupted or not, the interrupted status flag is cleared.
2. isInterrupted():
This method is an instance method of the Thread class. It checks whether the thread has been interrupted but does not clear the interrupted status flag. If the interrupted status flag is set, isInterrupted() returns true; otherwise, it returns false. Unlike interrupted(), calling isInterrupted() does not affect the interrupted status flag.
When to use interrupted() vs. isInterrupted() depends on whether you want to preserve the interrupt status of the thread or clear it after checking.
Let’s illustrate the usage of interrupted() and isInterrupted() methods in Java with an example:
java
public class InterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
// Simulating some work
Thread.sleep(2000);
} catch (InterruptedException e) {
// Thread was interrupted while sleeping
System.out.println("Thread interrupted");
}
});
thread.start();
// Interrupting the thread after some time
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
// Using interrupted() method
boolean wasInterrupted = Thread.interrupted(); // clears the interrupted status flag
System.out.println("Using interrupted() method: " + wasInterrupted);
// Using isInterrupted() method
boolean interruptedStatus = thread.isInterrupted(); // does not clear the interrupted status flag
System.out.println("Using isInterrupted() method: " + interruptedStatus);
}
}
Interrupted and Isinterrupted Example
In this example, a thread is created and started to simulate some work (sleeping for 2 seconds). After 1 second, the main thread interrupts the worker thread. Then, we use both interrupted() and isInterrupted() methods to check the interrupt status of the worker thread. The interrupted() method clears the interrupted status flag, so subsequent calls to isInterrupted() will return false. However, isInterrupted() does not clear the interrupted status flag, so it accurately reflects the interrupted status of the worker thread.