java - 为什么关闭 Java Executor 时要保留中断状态?

标签 java multithreading

关于 Java's ExecutionService 的文档,有一个关闭执行程序服务的示例方法,如下所示:

void shutdownAndAwaitTermination(ExecutorService pool) {
  pool.shutdown(); // Disable new tasks from being submitted
  try {
    // Wait a while for existing tasks to terminate
    if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
      pool.shutdownNow(); // Cancel currently executing tasks
      // Wait a while for tasks to respond to being cancelled
      if (!pool.awaitTermination(60, TimeUnit.SECONDS))
          System.err.println("Pool did not terminate");
    }
  } catch (InterruptedException ie) {
    // (Re-)Cancel if current thread also interrupted
    pool.shutdownNow();
    // Preserve interrupt status
    Thread.currentThread().interrupt();
  }
}

保留中断状态的目的是什么?

最佳答案

当您捕获 InterruptedException 时,当前线程上的中断标志将设置为 false。因此,您应该将其设置回 true,以便在该线程下执行的其他代码片段知道中断标志已设置,以防它们检查它。

大多数程序员可能不需要检查中断标志,我至少知道这在我们编写的企业代码中很少见。但对于库代码,最好在执行任何阻塞代码之前检查中断标志。否则,库代码可能会阻止线程(以及可能的应用程序)关闭。

因此,在捕获 InterruptedException 后,最好将中断标志设置回 true。

关于java - 为什么关闭 Java Executor 时要保留中断状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415437/

相关文章:

java - 将 SQLite 数据库中的数据显示到自定义 ListView

java - @jsonview of jackson 不使用 jax-rs

java - 我的工具栏太高,因此看起来很难看,并且下面的屏幕被裁剪,我该如何修复它?

Java 处理多个客户端 - 多线程?

JavaFX:线程 “JavaFX Application Thread” java.lang.RuntimeException 中的异常:java.lang.reflect.InitationTargetException

java - 从外部显示 ProgressDialog

java - 如何: set the selected "drop down list" value at run time

c++ - QNX C++线程问题

c - 使用管道进行线程通信的奇怪输出

c# - 在另一个线程中打开第二个 WPF 窗口?