I am bit confused with the behaviour of thread.isInterrupted
in the program below.
public class ThreadPractice {
public static void main(String args[]) throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("Starting thread..." + Thread.currentThread().getName());
Thread.sleep(10000);
System.out.println("Waking up");
}catch(InterruptedException e){
System.out.println("Thread is interrupted!!!");
Thread.currentThread().interrupt();
}
}
});
t.start();
Thread.sleep(2000);
t.interrupt();
//System.out.println(!t.isInterrupted());
while(!t.isInterrupted()){
System.out.println("Current thread not interrupted!!!");
}
}
}
When executing the above program as such, it prints,
Starting thread...Thread-0
Thread is interrupted!!!
But when I uncomment the System.out
statement to print the interrupt status, it runs into an infinite loop printing "Current thread not interrupted"
I am not able to figure out exactly what difference System.out
statement makes.
Note that I don't always get an infinite loop.
I suspect it is due to the interleaving of operations. It helps to also check if the thread is alive:
If the thread is not alive, its interrupted status is false.
I get an output like:
I guess the first loop sees the thread not interrupted because the
InterruptedException
has removed the flag - then you reset the flag withinterrupt()
in therun()
method and the thread can finish and is not alive any more.The next loop check sees it not alive and you start an infinite loop.
An interesting variation can be obtained by adding:
At the end of the
run()
method - it provides a delay long enough for the loop condition to be checked between the time the interrupted flag is reset and the time the thread dies.