繁体   English   中英

如何找出由 Executor.execute() (不是 ExecutorService )启动的线程/任务是否完成?

[英]How to find out if the thread/task started by Executor.execute() ( not ExecutorService ) completed?

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

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

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

暂无
暂无

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

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