[英]CompletableFuture completion sequence in JAVA
我寫了一個簡單的程序
import java.util.concurrent.*;
public class TestCompletableFuture {
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = new CompletableFuture<Void>()
.whenComplete((res, exc) -> {
System.out.println("inside handle.");
if (exc != null) {
System.out.println("exception.");
}
System.out.println("completed.");
}
);
future.completeExceptionally(new Exception("exception"));
System.out.println("finished.");
}
}
代碼的output:
finished.
當主線程調用future時,我的理解是。 提供給 CompletableFuture 的方法應該由 completeExceptionally() 調用。 當完成()。
為什么不是這樣呢?
這是你完成錯誤未來的結果。 要查看whenComplete
的運行情況,您必須獲得對第一步的引用並完成它:
public class TestCompletableFuture {
public static void main(String[] args) throws Exception {
/** get reference */
CompletableFuture<Void> future = new CompletableFuture<>();
/** configure the action that to be run when the future is complete */
CompletableFuture<Void> future2 = future
.whenComplete((res, exc) -> {
System.out.println("inside handle.");
if (exc != null) {
System.out.println("exception.");
}
System.out.println("completed.");
}
);
future.completeExceptionally(new Exception("exception"));
System.out.println("finished.");
}
}
代碼現在是不言自明的...運行(res, exc) ->
future
完成時的操作。 並簡單地在future
使用completeExceptionally(...)
來完成。
還需要注意的是此時所有上述階段(期貨)的異常完成:
System.out.println(future.isDone()); // true
System.out.println(future2.isDone()); // true
System.out.println(future.isCompletedExceptionally()); // true
System.out.println(future2.isCompletedExceptionally()); // true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.