我对下面程序中 thread.isInterrupted
的行为有点困惑。
public class ThreadPractice {
public static void main(String args[]) throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("Starting thread..." + Thread.currentThread().getName());
Thread.sleep(10000);
System.out.println("Waking up");
}catch(InterruptedException e){
System.out.println("Thread is interrupted!!!");
Thread.currentThread().interrupt();
}
}
});
t.start();
Thread.sleep(2000);
t.interrupt();
//System.out.println(!t.isInterrupted());
while(!t.isInterrupted()){
System.out.println("Current thread not interrupted!!!");
}
}
}
当执行上面的程序时,它打印,
Starting thread...Thread-0
Thread is interrupted!!!
但是当我取消注释 System.out
语句以打印中断状态时,它会进入无限循环打印“当前线程未中断”
我无法弄清楚 System.out
语句到底有什么不同。
最佳答案
请注意,我并不总是遇到无限循环。
我怀疑这是由于操作交错造成的。它还有助于检查线程是否存活:
System.out.println("Current thread not interrupted!!! Alive? " + t.isAlive());
如果线程不活动,则其中断状态为 false。
我得到如下输出:
Starting thread...Thread-0
Thread is interrupted!!!
Current thread not interrupted!!! Alive? true
Current thread not interrupted!!! Alive? false
[infinite loop]
我猜第一个循环看到线程没有被中断,因为 InterruptedException
已经删除了标志 - 然后你在 run 中用
方法和线程可以完成并且不再存在。interrupt()
重置标志()
下一个循环检查发现它不存在,于是你开始了一个无限循环。
一个有趣的变化可以通过添加:
System.out.println("Exiting Thread!!!");
在 run()
方法的末尾 - 它提供了足够长的延迟,以便在重置中断标志和线程结束之间检查循环条件。
关于java - 调用 thread.isInterrupted 并打印结果时的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490381/