I'm faced with strange behaviour. All sources tells that you need to call Thread.currentThread().interrupt() after you catch interrupt exception to restore interrupt flag. But i tried to create simple app that check interrupt status after process was interrupted
public class Main {
public static void main(String[] args) throws InterruptedException {
Runnable r = () -> {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
System.out.println("interrupted exception is occurred");
Thread.currentThread().interrupt();
System.out.println("interrupt flag is updated:" + Thread.currentThread().isInterrupted());
}
};
Thread thread = new Thread(r);
thread.start();
thread.interrupt();
boolean interruptFlag;
do {
Thread.sleep(1000);
interruptFlag = thread.isInterrupted();
System.out.println("interrupt flag:" + interruptFlag + " isAlive:" + thread.isAlive());
} while (!interruptFlag);
}
}
If you try ti run it then you get
interrupted exception is occurred
interrupt flag is updated:true
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
interrupt flag:false isAlive:false
It will work infinitely. The question is why iterrupt flag is false after the thread is dead?