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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With