Here is Java code for thread
public class WakeThread extends Thread{
public void run() {
boolean running = true;
while(running) {
try {
System.out.println("Going to sleep now");
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("***Thread is interrupted****");
running = false;
}
System.out.println("isInterrupted? : "+ isInterrupted());
}
}
public static void main(String[] args) throws InterruptedException {
WakeThread t = new WakeThread();
t.start();
Thread.sleep(2000);
t.interrupt();
}
}
Here is the output of the code
Going to sleep now
isInterrupted? : false
Going to sleep now
***Thread is interrupted****
isInterrupted? : false //I was expecting this to be true
I am unable to understand above behaviour, once the thread is interrupted I was expecting a true
result for isInterrupted but it still return false. Could someone please explain what that is happening?
Solution After reading the comments, I am now able to understand the behaviour. Solution as per comments and link is as follow
catch (InterruptedException e) {
Thread.currentThread().interrupt(); //this is the solution
System.out.println("***Thread is interrupted****");
running = false;
}