可能会出现不抛出异常
来源:5-4 遇到阻塞

Barea
2020-06-04
在多次运行后, 我发现有时候会不抛出异常线程就被停止了, 也就是说 Thread.currentThread().isInterrupted() 这个条件还是被用到了. 特别是如果我把sleep时间放的比较小, 比如1ms, 再把这个sleep放到while语句的顶端, 这个情况会更加普遍. 请问大家这是因为恰好程序运行到while loop中非sleep的地方(比如运行到num++处)然后被打断, 导致在下一次进入while loop时触发了 Thread.currentThread().isInterrupted() 这个条件吗?
我的代码:
public class RightWayStopThreadWithSleepEveryLoop {
public static void main(String[] args) throws InterruptedException {
Runnable runnable =
() -> {
int num = 0;
try {
while (num <= 10000 && !Thread.currentThread().isInterrupted()) {
Thread.sleep(1);
if (num % 100 == 0) {
System.out.println(num + " is the multiple of 100.");
}
num++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread thread = new Thread(runnable);
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
写回答
1回答
-
恩,你的理解是对的
132020-06-04
相似问题