可能无意中会出现抛出异常但是线程没有关闭的场景
来源:5-4 遇到阻塞

ID_tony
2019-11-11
老师 自己胡乱调整了try catch的位置:
Runnable runnable2 = ()->{
int num=0;
while(num<=10000) {
if(num % 100 == 0) {
System.out.println(num+"是100的倍数");
System.out.println(Thread.currentThread().getName());
}
num++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
会抛出sleep interrupted异常,但是该程序没有关闭,还会继续执行下去,好像并不是只要有中断请求响应,线程就会关闭。为什么会出现继续执行这种情况?实际开发过程中如何避免我这种错误的处理方法?如何进行彻底关闭呢?
写回答
3回答
-
@Override public void run() { int num = 0; while (num <= 10000) { if (num % 100 == 0) { System.out.println(num + "是100的倍数"); } num++; // 注意,这是try-catch在循环内的情况。 try { // 当sleep抛出InterruptedException时,这个“任务”抛出的异常被catch为“正常”, // 因此“任务”抛出异常通知没有触碰到子线程,子线程认为“任务”依然是正常运行,因此不会响应期望者(主线程)。 // 即:子线程没有发现自己该结束了。 Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } // while结束 }
@Override public void run() { int num = 0; // 注意,这是try-catch包含全部while循环的情况 // while循环是整个业务逻辑,当catch异常后,整个run方法的任务就执行完毕,线程完美停止。 try { // num<=300 && 本线程并没有被期望停止 while (num <= 300 && !Thread.currentThread().isInterrupted()) { if (num % 100 == 0) { System.out.println("num = " + num); } num++; } System.out.println("打印完毕,子线程进入sleep"); Thread.sleep(10 * 1000); System.out.println("子线程sleep完毕,任务圆满结束。"); } catch (InterruptedException e) { // 子线程在睡眠中被通知停止,抛出 InterruptedException: sleep interrupted // 这是比较特殊的通知方式,告知调用方子线程(本线程)已经停止。 e.printStackTrace(); } }
012019-11-25 -
ID_tony
提问者
2019-11-11
针对该问题,为什么会继续执行下去是不是要看抛出异常以后jvm对线程的处理方式?其实抛出异常以后程序并没有真正的停止,根据异常种类决定是否停止线程?
00 -
ID_tony
提问者
2019-11-11
老师抱歉 下一章节有相关问题阐述
00
相似问题