Java Threads isInterrupted(), why this output is not appearing

Viewed 61

I am playing around with threads and found some curious output from my program that I'm having trouble understanding. Here is my Self class:

public class Self {

    public static void main(String[] args) {
        System.out.println("Hello from main");
       
        Thread t = Thread.currentThread();
       
        if (Thread.interrupted()) {
            System.out.println("Message 0A");
        } else {
            System.out.println("Message 0B");
        }
       
        t.interrupt();
       
        if (t.isInterrupted()) {
            System.out.println("Message 1A");
        } else {
            System.out.println("Message 1B");
        }
       
        if (Thread.interrupted()) {
            System.out.println("Message 2A");
        } else {
            System.out.println("Message 2B");
        }
       
        if (t.isInterrupted()) {
            System.out.println("Message 3");
        }
       
        System.out.println("Back from where ever I was");
    }
}

And here is my output from the Self class:

Hello from main
Message 0B
Message 1A
Message 2A
Back from where ever I was

Why does "Message 3" never get printed? And why does "Back from where ever I was" always appear after any message related to thread t?

1 Answers

The message "Message 3" is not displayed because 'the interrupted status' of the main thread has been cleared by the call Thread.interrupted(). That is the key distinction between the instance method isInterrupted and the static method interrupted. The former does NOT clear the 'interrupted status'.

Check out javadoc for more details. https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted()

Related