java - ThreadpoolExecutor ,当其中一个正在运行的线程抛出异常时,正在等待其他正在运行的线程完成
问题描述
问题陈述:我在循环中使用ThreadPoolExecutor来调用窗口进程(Abby)进行文本文件处理。一次有 5 个线程在运行,它们调用窗口进程。但在某些情况下,一个或多个正在运行的线程会抛出异常。在这种情况下,我希望允许其他正在运行的线程完成它们的任务,并且在运行线程完成后优雅地处理抛出异常的线程。我怎样才能做到这一点? 到目前为止,我知道一旦发生异常,我们可以使用ThreadExecutionCompletionService并取消其他正在运行的线程,但我的情况不同 - 我希望其他正在运行的线程完成
ExecutorService executorService = Executors.newCachedThreadPool();
final ExecutorCompletionService<String> completionService =
new ExecutorCompletionService<String>(executorService);
for (int i = 0; i < 10; ++i) {
completionService.submit(new Task());
}
解决方案
怎么样(请注意,您必须根据自己的用途进行调整):
ExecutorService executorService = Executors.newCachedThreadPool();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
futures.add(CompletableFuture.runAsync(
() -> {
// do work here and return
return work
},executorService)
.exceptionally(e -> {
logger.error("Error here"+e);
return null;
})
);
}
CompletableFutre.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
推荐阅读
- c - 从头开始在 C 中反转字符串
- python - 当约束在 OpenMDAO 中计算为无穷大时,最好的处理方法是什么?
- tmux - 从插入模式切换到正常模式时neovim屏幕滞后
- python - 将映射 long/lat 代码从 R (sp pkg) 转换为 Python
- javascript - 当通过nodemailer -node.js作为电子邮件发送时,html中的图像不显示?
- python - 使用 Flask-Dropzone 一次上传多个文件
- amazon-web-services - 每个通配符子域指向不同的IP地址
- c# - 如何忽略继承中的歧视列
- pandas - Pandas:将多个列键上的两个数据集与匹配行的条件联合起来
- excel - Excel添加在启动时不加载