java - 如何确定由 Executor.execute() (不是 ExecutorService )启动的线程/任务是否完成?
问题描述
在 Java 中,Executor 类没有像 ExecutorService 子类那样的 shutdown/shutdownNow()/awaitTermination。因此,如果您通过调用 executorObject.execute(runnableTask) 启动任务/线程,如何检查该任务是否已完成?
解决方案
您不能Executor
仅仅因为它提供了一个方法就这样做void execute(Runnable)
。除非您考虑使用Executor
return 的实现,否则您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);
推荐阅读
- spring-boot - 我想获取 MongoTemplate 的 findAndModify 返回值作为修改值
- python - plotly px.scatter_3d 标记大小
- gdb - gdb 自动继续等待 ENTER?
- python - 在 Linux 上安装 pickle5 时出现终端错误
- javascript - 如何使用NodeJS替换作为Json对象值键的字符串
- webdriver - Codeception Webdrivers - 我可以在打开页面之前设置 cookie 吗?
- javascript - Vue 3:如何使用组合 API 正确更新组件道具值?
- vue.js - Vue 3 cli-service 应用程序:当从其他组件导入带有插槽的组件时,“插槽“默认”在渲染函数之外调用”警告
- airflow - 如何以少于 1 分钟的间隔运行 dag
- c# - 从字典中指定的类型转换为 IList 类型