一、什麼是CompletableFuture
CompletableFuture是Java8中的一個非同步編程工具,它繼承了Future的特點,同時又支持了回調函數和非同步編程。
以往在Java中實現非同步編程需要使用Future或者線程池,但是Future的局限性在於無法組合多個非同步操作,也無法實現回調函數,而線程池更多的是用於IO密集型的代碼優化,對於計算密集型的代碼並不是最優選擇。因此Java8引入了CompletableFuture,它可以讓非同步編程變得更加容易,通過不同的非同步操作可以對它們進行排序、組合以及轉換,簡化了複雜的非同步編程。
二、CompletableFuture的使用方法
CompletableFuture有兩種操作方式:
1、非同步執行代碼
“`
CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return “Hello World!”; //返回結果
}).thenAccept(result -> {
//執行完成後的回調函數
System.out.println(result);
}).exceptionally(ex -> {
ex.printStackTrace();
return null;
});
“`
2、組合多個CompletableFuture進行操作
“`
CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return 1;
});
CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return 2;
});
CompletableFuture future3 = CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return 3;
});
CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3)
.thenApply(v -> Stream.of(future1, future2, future3)
.map(CompletableFuture::join)
.reduce(0, Integer::sum));
combinedFuture.thenAccept(result -> {
//執行完成後的回調函數
System.out.println(“結果是:” + result);
});
“`
三、CompletableFuture的其他方法介紹
除了上述兩種使用方法外,CompletableFuture中還有很多其他的方法可以使用:
1、thenApply方法:用於將CompletableFuture中的結果進行轉換
“`
CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return “Hello World!”;
}).thenApply(result -> {
//對結果進行轉換
return result + ” My name is John.”;
}).thenAccept(System.out::println);
“`
2、thenCompose方法:將當前CompletableFuture和另一個CompletableFuture進行組合
“`
CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return 1;
});
CompletableFuture future2 = future1.thenCompose(i -> CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return i + 2;
}));
future2.thenAccept(result -> {
//執行完成後的回調函數
System.out.println(“結果是:” + result);
});
“`
3、handle方法:對CompletableFuture返回的結果和異常進行處理
“`
CompletableFuture.supplyAsync(() -> {
//非同步執行的代碼
return 1 / 0; //拋出異常
}).handle((result, ex) -> {
if (ex != null) {
System.out.println(“發生異常:” + ex.getMessage());
}
return result;
}).thenAccept(System.out::println);
“`
四、注意點
1、CompletableFuture不支持取消任務
2、CompletableFuture中的任務是非同步執行的,並不能保證它們的執行順序
3、使用CompletableFuture需要對回調函數進行異常處理
4、CompletableFuture可以通過多種方法進行組合和轉換
五、總結
CompletableFuture是Java8中新增的非同步編程工具,它的出現簡化了非同步編程,讓代碼更加簡潔明了。通過多種方法可以對CompletableFuture進行操作,比如組合、轉換和異常處理等。使用CompletableFuture需要注意一些細節,比如不能取消任務、不能保證任務的執行順序等。總體來說,CompletableFuture是一個非常值得學習的工具。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/255023.html