[英]How to end a task(timeout a thread) (by rising interrupt) using executor.execute and future.get() without blocking the main thread
[英]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.