Why thread.isInterrupted () returns false even after calling Thread.currentThread (). Interrupt ()

advertisements

When I run this test, why does sleepThread.isInterrupted() always return false?

(I had to execute Thread.currentThread().interrupt() to set the interrupted flag when catch a InterruptedException).

@Test
public void t() {
    Thread sleepThread = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                System.out.println("have been interruptted....");
                e.printStackTrace();

                Thread.currentThread().interrupt();

                // in here this.isInterrupted() will return true
                System.out.println("now , instant interrupt flag : "
                + this.isInterrupted());
            }
        }
    };
    sleepThread.start();

    try {
        sleepThread.interrupt();
        Thread.sleep(2 * 1000);

        // in here ,why sleepThread.isInterrupted() return false ?
        System.out.println("sleep thread interrupt flag : "
        + sleepThread.isInterrupted());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

This is the output:

have been interruptted
now , instant interrupt flag : true
java.lang.InterruptedException: sleep interrupted
   at java.lang.Thread.sleep(Native Method)
   at com.roundwith.concurrent.Interrupt_Test$1.run(Interrupt_Test.java:15)
sleep thread interrupt flag : false


It's because by the time the last statement is reached

System.out.println("sleep thread interrupt flag : " + sleepThread.isInterrupted());

the thread would be dead.

Try to remove the 2-second sleep in the main thread and you would see the difference (try several runs -- it may still print false but at least the main thread has a chance to see the other thread alive).