Different behaviour when calling thread.isInterrupted and printing the result
Asked Answered
R

1

12

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.

Reason answered 15/12, 2014 at 18:12 Comment(0)
G
5

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.

Gaultheria answered 15/12, 2014 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.