这是线程的
的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;
}