小编Abh*_*iya的帖子

为什么 InterruptedException 只从 sleep() 和 wait() 等阻塞方法抛出?

如果我编写如下代码,我们不能中断或终止线程。它也不会抛出 InterruptedException。

Thread loop = new Thread(
  new Runnable() {
    @Override
    public void run() {
      while (true) {
      }
    }
  }
);
loop.start();
loop.interrupt();
Run Code Online (Sandbox Code Playgroud)

要中断这个线程,我需要修改我的代码如下:

Thread loop = new Thread(
  new Runnable() {
    @Override
    public void run() {
      while (true) {
        if (Thread.interrupted()) {
          break;
        }
        // Continue to do nothing
      }
    }
  }
);
loop.start();
loop.interrupt();
Run Code Online (Sandbox Code Playgroud)

我的问题是,

  1. 为什么 Java 的设计方式是只有在像 sleep() 和 wait() 这样的阻塞方法的情况下才会抛出InterruptedException

  2. 为什么在普通代码中,我们需要像上面的代码片段那样手动处理?为什么每当我们通过interrupt()方法将中断标志设置为 true 时,Java 不会抛出 InterruptedException ?

我已经阅读了很多关于 InterruptedException 的博客和文章,但没有找到任何令人信服的答案。

编辑

找到关于 …

java multithreading sleep wait interrupted-exception

1
推荐指数
1
解决办法
1316
查看次数