首页 > 解决方案 > 如何确定由 Executor.execute() (不是 ExecutorService )启动的线程/任务是否完成?

问题描述

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

标签: javamultithreading

解决方案


您不能Executor仅仅因为它提供了一个方法就这样做void execute(Runnable)。除非您考虑使用Executorreturn 的实现,否则您Future可以实现自己的通知/等待机制:

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

推荐阅读