Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在关闭Java执行器时要保留中断状态?_Java_Multithreading - Fatal编程技术网

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

为什么在关闭Java执行器时要保留中断状态?,java,multithreading,Java,Multithreading,在的文档中,有一个关闭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, Time

在的文档中,有一个关闭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();
  }
}

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

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

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


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

在这种特定情况下还是一般情况下?我想你是在问一般情况。@Kayaman:我想是一般情况吧。我试图理解这个示例代码。通常,保留中断状态是可取的,而不仅仅是在关闭Java执行器时。比如说,,