Different behaviour when calling thread.isInterrupted and printing the result Different behaviour when calling thread.isInterrupted and printing the result multithreading multithreading

Different behaviour when calling thread.isInterrupted and printing the result


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:

System.out.println("Current thread not interrupted!!! Alive? " + t.isAlive());

If the thread is not alive, its interrupted status is false.

I get an output like:

Starting thread...Thread-0
Thread is interrupted!!!
Current thread not interrupted!!! Alive? true
Current thread not interrupted!!! Alive? false
[infinite loop]

I guess the first loop sees the thread not interrupted because the InterruptedException has removed the flag - then you reset the flag with interrupt() in the run() 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:

System.out.println("Exiting Thread!!!");

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.