[英]How to pause work in particular thread running in ThreadPoolExecutor
[英]ThreadpoolExecutor , Waiting for other running thread to complete when one of the running thread throws exception
問題陳述 :我正在循環中使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.