sleep()清除中断标记的问题
来源:5-6 抛出异常

大魔王kite
2021-05-28
package cn.java.threadcoreknowledge.stopthread;
public class RightStopThreadInProd implements Runnable {
@Override
public void run() {
while(true && !Thread.currentThread().isInterrupted()) {
System.out.println("go");
try {
throwInMethod();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void throwInMethod() throws InterruptedException {
Thread.sleep(2000);
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new RightStopThreadInProd());
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
这是照着课程敲的代码,我有两个地方不懂:
我的理解是throwInMethod方法中的sleep方法接收到中断信息后会清除中断标记,那么循环条件中的“!Thread.currentThread().isInterrupted()“有什么用呢?
2:为什么执行该代码后,程序抛出异常后依旧继续执行循环,而不是停止呢?
写回答
1回答
-
悟空
2021-05-28
1. 为了处理这种情况:还没执行到sleep,就被!Thread.currentThread().isInterrupted()判断到了。
2.因为异常被catch住了
122021-06-19
相似问题