常用场景:
1.并行执行多个任务:CompletableFuture
可以用于并行执行多个任务,从而提高性能
2.并行执行多个任务:CompletableFuture
可以用于并行执行多个任务,从而提高性能
3.任务依赖和组合:CompletableFuture
允许您创建任务之间的依赖关系,以便在一个任务完成后执行另一个任务。
4.异常处理:您可以使用 CompletableFuture
来处理异步任务中可能出现的异常。
常用方法:
-
supplyAsync(Supplier<U> supplier)
:创建一个异步任务,并返回一个CompletableFuture
,它将由supplier
提供的结果作为计算结果。 -
thenApply(Function<T, U> fn)
:对CompletableFuture
的结果应用一个函数,返回一个新的CompletableFuture
。 -
thenCompose(Function<T, CompletableFuture<U>> fn)
:将两个CompletableFuture
对象的结果组合在一起,产生一个新的CompletableFuture
。 -
exceptionally(Function<Throwable, T> fn)
:处理异常情况,返回一个默认值或另一个CompletableFuture
。 -
allOf(CompletableFuture<?>... cfs)
:等待多个CompletableFuture
完成。 -
anyOf(CompletableFuture<?>... cfs)
:等待任何一个CompletableFuture
完成。
案例
@Test
public void testDemo(){
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 2;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Integer> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + result2);
combinedFuture.thenAccept(result -> System.out.println("Combined result: " + result));
try {
// 等待所有任务完成
CompletableFuture.allOf(future1, future2, combinedFuture).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
大牛链接: