简体   繁体   English

如何知道java中的ExecutorService中是否有正在运行的任务?

[英]How to know whether there're running tasks in ExecutorService in java?

I'd like to allow the program continue until all the tasks in ExecutorService is done. 我想让程序继续,直到ExecutorService中的所有任务完成。 And I don't want to shutdown it, I use it later. 而且我不想关闭它,我稍后再使用它。 How can I achieve this ? 我怎样才能做到这一点? Thanks 谢谢

Use ExecutorService#shutdown() followed by ExecutorService#awaitTermination() to make your main thread wait for all the submitted tasks to complete before it exits. 使用ExecutorService#shutdown()后跟ExecutorService#awaitTermination()使main线程在退出之前等待所有提交的任务完成。 From the docs for 来自文档

ExecutorService#awaitTermination() ExecutorService的#awaitTermination()

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first. 阻止所有任务在关闭请求之后完成执行,或者发生超时,或者当前线程被中断,以先发生者为准。

An example taken directly from the ExecutorService Javadoc: 直接从ExecutorService Javadoc获取的示例:

http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html

The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks: 以下方法分两个阶段关闭ExecutorService,首先调用shutdown以拒绝传入的任务,然后在必要时调用shutdownNow以取消任何延迟的任务:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM