【问题标题】:How to find out if the thread/task started by Executor.execute() ( not ExecutorService ) completed?如何确定由 Executor.execute() (不是 ExecutorService )启动的线程/任务是否完成?
【发布时间】:2019-04-01 01:44:08
【问题描述】:

在Java中,Executor类没有像ExecutorService子类那样的shutdown/shutdownNow()/awaitTermination。因此,如果您通过调用 executorObject.execute(runnableTask) 启动任务/线程,您如何检查该任务是否已完成?

【问题讨论】:

  • 如果您可以控制 Runnable 的代码,您可以在其 run 方法的末尾添加一些内容。否则,除非 Executor 恰好是 ExecutorService,否则无法知道任务何时运行。

标签: java multithreading


【解决方案1】:

你不能用Executor 来做这件事,仅仅因为它提供了一个单一的方法void execute(Runnable)。除非您考虑使用返回 FutureExecutor 实现,否则您可以实现自己的通知/等待机制:

final CountDownLatch latch = new CountDownLatch(1);
Runnable task = () -> {
   try {
      // ... do useful work
   } finally {
      latch.countDown();
   }
}

executorObject.execute(task);

// wrap into try/catch for InterruptedException
// if not propagating further
latch.await(); // await(timeout);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多