前面我们已经介绍了几个静态办法:completedFuture、runAsync、supplyAsync,下面介绍的┞封两个办法用来组合多个CompletableFuture。
- CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
- return 100;
- });
- CompletableFuture<Void> f = future.thenAcceptBoth(CompletableFuture.completedFuture(10), (x, y) -> System.out.println(x * y));
- System.out.println(f.get());
可以看到Action的类型是BiConsumer<? super T,? super Throwable>,它可以处理正常的计算结不雅,或者异常情况。
- public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
- public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
例子如下:
allOf办法是当所有的CompletableFuture都履行完后履行计算。
anyOf办法是当随便率性一?CompletableFuture履行完后就会履行计算,计算的结不雅雷同。
下面的代码运行结不雅有时是100,有时是"abc"。然则anyOf和applyToEither不合。anyOf接收随便率性多的CompletableFuture,然则applyToEither只是断定两个CompletableFuture。anyOf返回值的计算结不雅是参数中个一一个CompletableFuture的计算结不雅,applyToEither返回值的计算结不雅倒是要经由fn处理的。当然还有静态办法的差别,线程池的选择等。
- Random rand = new Random();
- CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
- try {
- Thread.sleep(10000 + rand.nextInt(1000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return 100;
- });
- CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
- try {
- Thread.sleep(10000 + rand.nextInt(1000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
推荐阅读
【限时免费】岁尾最强一次云计算大年夜会,看传统、社区、互联网企业若何碰撞?【编辑推荐】2017 Android和iOS几回再三被曝Bug,它们都怎么了?谷歌苹不雅竟齐翻车!谈谈安卓8/iOS11那些BugiOS消息转发>>>详细阅读
地址:http://www.17bianji.com/lsqh/40058.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示