Sobes.tech
Middle

What is the difference between the interrupted() and isInterrupted() methods in Java?

sobes.tech AI

Answer from AI

isInterrupted() checks whether the current thread has the interrupt flag set, without resetting it.

interrupted() checks whether the current thread has the interrupt flag set, and resets it after the check if it was set. This method is static.

Example:

// Create a thread
Thread t = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        // Perform useful work
    }
    System.out.println("Thread interrupted.");
});

// Start the thread
t.start();

// Interrupt the thread
t.interrupt();

// Check the flag state after interrupt() with isInterrupted()
System.out.println("isInterrupted() after interrupt(): " + t.isInterrupted()); // Should be true

try {
    // Wait for the thread to finish (in this case, it will finish quickly)
    t.join();
} catch (InterruptedException e) {
    // Restore the interrupt flag if join() was interrupted
    Thread.currentThread().interrupt();
}

// Check the flag state after interrupt() with interrupted() (from another thread!)
// Note: Calling interrupted() from another thread doesn't make sense,
// as interrupted() works with the flag of the currently executing thread.
// To demonstrate interrupted() working, call it from the interrupted thread itself.

// Example of calling interrupted() inside another thread (not related to thread t's flag)
System.out.println("interrupted() from current thread: " + Thread.interrupted()); // Should be false (if current thread was not interrupted)

Key differences:

Method Does the interrupt flag reset? Method type
isInterrupted() No Instance
interrupted() Yes Static