13
下面是我的代碼CompletableFuture.get()和CompletableFuture.join()之間的區別:
List<String> process() {
List<String> messages = Arrays.asList("Msg1", "Msg2", "Msg3", "Msg4", "Msg5", "Msg6", "Msg7", "Msg8", "Msg9",
"Msg10", "Msg11", "Msg12");
MessageService messageService = new MessageService();
ExecutorService executor = Executors.newFixedThreadPool(4);
List<String> mapResult = new ArrayList<>();
CompletableFuture<?>[] fanoutRequestList = new CompletableFuture[messages.size()];
int count = 0;
for (String msg : messages) {
CompletableFuture<?> future = CompletableFuture
.supplyAsync(() -> messageService.sendNotification(msg), executor).exceptionally(ex -> "Error")
.thenAccept(mapResult::add);
fanoutRequestList[count++] = future;
}
try {
CompletableFuture.allOf(fanoutRequestList).get();
//CompletableFuture.allOf(fanoutRequestList).join();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapResult.stream().filter(s -> !s.equalsIgnoreCase("Error")).collect(Collectors.toList());
}
我試圖與這兩種方法,但沒有什麼區別結果。
謝謝
'得到()'需要你捕獲檢查的異常。當你從'get()'改變到'join()'時你應該注意到它的區別,因爲你會立即得到一個編譯器錯誤,說'try'塊中沒有拋出'InterruptedException'和'ExecutionException'。 – Holger
@ holi-java:'join()'不能被打斷。 – Holger
@霍爾是的,先生。我發現我不能打斷任務。 –