老师您好,为什么我测试时,try/catch在while内外运行结果都一样呢?
来源:5-5 中断信号

丨木頭丶吅
2021-10-21
public static void interrupt() throws InterruptedException {
Runnable runnable = () ->{
int num = 0;
while (num<=300){
if(num%100==0){
System.out.println(num+ "是100的倍数");
}
num++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
Thread.sleep(500);
thread.interrupt();
}
运行结果:
0是100的倍数
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.exercise.unsafe.InterruptTest.lambda$interrupt$0(InterruptTest.java:18)
at java.lang.Thread.run(Thread.java:748)
写回答
2回答
-
cqnuhy
2022-03-19
什么原因?持续关注中
00 -
悟空
2021-10-21
你现在这种写法,中断会被catch,然后while会继续运行的。
try/catch在while内外的逻辑是不一样的,如果catch住,那么就不会退出while
062021-10-27
相似问题