ThreadpoolExecutor ,当 运行 线程之一抛出异常时等待其他 运行 线程完成
ThreadpoolExecutor , Waiting for other running thread to complete when one of the running thread throws exception
问题陈述:我在循环中使用ThreadPoolExecutor为文本文件window进程(Abby)调用processing.At 一次有 5 个线程 运行 调用 window 进程。但在某些情况下,一个或多个 运行 线程会抛出异常。
在这种情况下,我想允许其他 运行 个线程完成它们的任务,并且抛出异常的线程在 运行 个线程完成后得到妥善处理。 我该怎么做?
到目前为止,我知道一旦发生异常,我们可以使用 ThreadExecutionCompletionService 和 cancel 其他 运行 线程
但我的情况不同 - 我希望其他 运行 个线程完成
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();
问题陈述:我在循环中使用ThreadPoolExecutor为文本文件window进程(Abby)调用processing.At 一次有 5 个线程 运行 调用 window 进程。但在某些情况下,一个或多个 运行 线程会抛出异常。 在这种情况下,我想允许其他 运行 个线程完成它们的任务,并且抛出异常的线程在 运行 个线程完成后得到妥善处理。 我该怎么做? 到目前为止,我知道一旦发生异常,我们可以使用 ThreadExecutionCompletionService 和 cancel 其他 运行 线程 但我的情况不同 - 我希望其他 运行 个线程完成
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();