Java 中 CompletableFuture的方法thenCombineAsync()与thenCombine() 的区别
Java 中 CompletableFuture的方法thenCombineAsync()与thenCombine()有什么区别呢,首先我们来看一下他们的主要功能:
- thenCombine 会把 两个 CompletionStage 的任务都执行完成后,把两个任务的结果一块交给 thenCombine 来处理。
- 当两个CompletionStage都执行完成后,把结果一块交给thenAcceptBoth来进行消耗
thenAcceptBoth和thenCombine都是CompletableFuture中的方法,它们的区别在于:
thenAcceptBoth方法:接收两个CompletableFuture对象,等待这两个对象都完成后执行一个消费者函数(Consumer),将这两个对象的结果传递给该函数进行处理,但是不会返回任何结果。
thenCombine方法:接收两个CompletableFuture对象,等待这两个对象都完成后执行一个合并函数(BiFunction),将这两个对象的结果传递给该函数进行处理,并返回合并后的结果。
因此,thenAcceptBoth方法适用于需要在两个任务完成后执行一个操作的场景,而thenCombine方法适用于需要在两个任务完成后将它们的结果进行合并的场景。
private static void thenCombineTest() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{return 1;});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{return 2;});
String result = f1.thenCombine(f2, (f1Result,F2Result) ->{
return "f1="+f1Result+";f2="+F2Result+";";
}).join();
System.out.println(result);
}
private static void thenAcceptBothTest() throws Exception {
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(()->{return 1;});
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(()->{return 2;});
f1.thenAcceptBoth(f2, (f1Result,F2Result) ->{
System.out.println("f1="+f1Result+";f2="+F2Result+";");
});
}