有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程为什么在关闭Java执行器时要保留中断状态?

Java's ExecutionService的文档中,有一个关闭executor服务的示例方法,如下所示:

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();
  }
}

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


共 (1) 个答案

  1. # 1 楼答案

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

    大多数程序员可能不必检查中断标志,至少我知道这在我们编写的企业代码中很少见。但是对于库代码来说,在执行任何阻塞代码之前检查中断标志是一个好主意。否则,库代码可能会阻止线程(可能还有应用程序)关闭

    因此,在捕捉到InterruptedException之后,最好将中断标志设置回true