老师您好,为什么我测试时,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

什么原因?持续关注中

0
0

悟空

2021-10-21

你现在这种写法,中断会被catch,然后while会继续运行的。

try/catch在while内外的逻辑是不一样的,如果catch住,那么就不会退出while

0
6
悟空
回复
丨木頭丶吅
我还没碰到过类似的问题,我不确定是不是spring的问题,我怀疑spring应该没啥问题。。
2021-10-27
共6条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程