0

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;
}
PHP Avenger
  • 1,744
  • 6
  • 37
  • 66
  • 2
    The official API documentation already does that. Start from there. – Marko Topolnik Aug 06 '15 at 12:03
  • 1
    Also see e.g. http://www.javaspecialists.eu/archive/Issue056.html . As a rule of thumb, I'm generally using the pattern of `...catch (InterruptedException e) { Thread.currentThread().interrupt(); ... }` to alleviate this problem. – Marco13 Aug 06 '15 at 12:07
  • I will read the provided link now, but I was expecting an answer in plain English. Thanks for quick reply. – PHP Avenger Aug 06 '15 at 12:28
  • 1
    @NetSurgeon: [StephenC's answer](http://stackoverflow.com/a/7142831/217324) on the linked question should say about all there is to say about this. – Nathan Hughes Aug 06 '15 at 12:48
  • Thanks, It helped the reason part – PHP Avenger Aug 06 '15 at 13:13

0 Answers0