可能会出现不抛出异常

来源: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回答

悟空

2020-06-04

恩,你的理解是对的

1
3
悟空
回复
Barea
恩对的,你理解的很深刻,就是这样的,不加的话,则下次循环时一定会抛出异常
2020-06-04
共3条回复

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

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

2512 学习 · 939 问题

查看课程