3

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
dimo414
  • 47,227
  • 18
  • 148
  • 244
  • here is a similar question didn't resolve : [Thread.isInterrupted always returns false](http://stackoverflow.com/questions/20677604/thread-isinterrupted-always-returns-false) – Amy Microgoo Aug 24 '15 at 17:59
  • Sidebar: This looks like an ill-advised way to use interrupts. What kind of behavior are you after, and why do you need it? – Snild Dolkow Aug 24 '15 at 19:23

2 Answers2

0

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).

M A
  • 71,713
  • 13
  • 134
  • 174
  • You *may* see the difference. There is still no guarantee that the "main" thread here will have time to see the sleep thread before it dies. – Snild Dolkow Aug 24 '15 at 19:22
0

try to change,

Thread.sleep(2 * 1000);

to

//Thread.sleep(2 * 1000);