Java Thread:为什么isInterrupted为后面的代码

时间:2015-08-06 12:01:23

标签: java multithreading

这是线程的

的Java代码
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();
    }
}

以下是代码的输出

Going to sleep now
isInterrupted? : false
Going to sleep now
***Thread is interrupted****
isInterrupted? : false //I was expecting this to be true

我无法理解上面的行为,一旦线程被中断,我期待isInterter的true结果,但它仍然返回false。有人可以解释一下发生了什么吗?

解决方案 阅读评论后,我现在能够理解这种行为。 根据评论和链接的解决方案如下

catch (InterruptedException e) {
    Thread.currentThread().interrupt(); //this is the solution
    System.out.println("***Thread is interrupted****");
    running = false;
}

0 个答案:

没有答案