[英]CompletableFuture is Not waiting for child threads
我正在嘗試等待processor.processFiles()
完成,該方法返回 void,它是一個 @Async 方法。 忙等待邏輯不會導致進程等待方法完成。 有人可以指出我錯過了什么嗎?
try{
filesList.forEach(files -> {
List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
files.forEach(file-> {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() ->
processor.processFiles());
completableFutures.add(completableFuture);
});
while(true) {
Thread.sleep(5000);
boolean isComplete = completableFutures.stream().allMatch(result -> result.isDone() == true);
if(isComplete){
break;
}
LOGGER.info("processing the file...");
}
});
}
catch(Exception e){
}
finally{
closeConnections();
}
我認為你把事情復雜化了。
fileList.flatMap(List::stream).parallel().forEach(file -> processor.processFiles());
forEach 將並行運行,並在處理完所有文件后返回。
至少,不要使用副作用來填充List
。
List<CompletableFuture<Void>> completableFutures = files.stream().map(
file -> CompletableFuture.runAsync(() -> processor.processFiles());
).collect( Collectors.toList());
我同意這個評論。
CompletableFuture<Void> all = CompletableFuture.allOf( completableFutures );
然后你可以使用get
,它會等到任務完成。
另一種方法是跳過 List + CompletableFuture.allOf 並只返回一個可完成的未來。
CompletableFuture<Void> all = files.stream().map(
file -> CompletableFuture.runAsync(
() -> processor.processFiles()
)
).collect(
Collectors.reducing(
CompletableFuture.completedFuture(null), CompletableFuture::allOf
)
);
這會將 map file
寫入 CompletableFuture,然后將所有生成的可完成未來合並為一個可完成未來。 你可以調用它,它會在一切完成后返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.