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