更改网站建设报价,郑州网页制作案例教程,信息类网站有哪些,涿州李战彪使用BiFunction处理两个阶段的结果
如果CompletableFuture依赖两个前面阶段的结果#xff0c; 它复合两个阶段的结果再返回一个结果#xff0c;我们就可以使用thenCombine()函数。整个流水线是同步的#xff0c;所以getNow()会得到最终的结果#xff0c;它把大写和小写字符…使用BiFunction处理两个阶段的结果
如果CompletableFuture依赖两个前面阶段的结果 它复合两个阶段的结果再返回一个结果我们就可以使用thenCombine()函数。整个流水线是同步的所以getNow()会得到最终的结果它把大写和小写字符串连接起来。
static void thenCombineExample() {String original Message;CompletableFuture cf CompletableFuture.completedFuture(original).thenApply(s - delayedUpperCase(s)).thenCombine(CompletableFuture.completedFuture(original).thenApply(s - delayedLowerCase(s)),(s1, s2) - s1 s2);assertEquals(MESSAGEmessage, cf.getNow(null));
} 异步使用BiFunction处理两个阶段的结果
类似上面的例子但是有一点不同依赖的前两个阶段异步地执行所以thenCombine()也异步地执行即时它没有Async后缀。
Javadoc中有注释
Actions supplied for dependent completions of non-async methods may be performed by the thread that completes the current CompletableFuture, or by any other caller of a completion method
所以我们需要join方法等待结果的完成。
static void thenCombineAsyncExample() {String original Message;CompletableFuture cf CompletableFuture.completedFuture(original).thenApplyAsync(s - delayedUpperCase(s)).thenCombine(CompletableFuture.completedFuture(original).thenApplyAsync(s - delayedLowerCase(s)),(s1, s2) - s1 s2);assertEquals(MESSAGEmessage, cf.join());
}