作家
登录

Java CompletableFuture详解

作者: 来源: 2017-12-22 09:13:58 阅读 我要评论

  •  
  •         e.printStackTrace(); 
  •  
  •     } 
  •  
  •     return 200; 
  •  
  • }); 
  •  
  • CompletableFuture<String> f =  future.applyToEither(future2,i -> i.toString());  
  • 前面我们已经介绍了几个静态办法:completedFuture、runAsync、supplyAsync,下面介绍的┞封两个办法用来组合多个CompletableFuture。

    1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
    2.  
    3.     return 100; 
    4.  
    5. }); 
    6.  
    7. CompletableFuture<Void> f =  future.thenAcceptBoth(CompletableFuture.completedFuture(10), (x, y) -> System.out.println(x * y)); 
    8.  
    9. System.out.println(f.get()); 

    可以看到Action的类型是BiConsumer<? super T,? super Throwable>,它可以处理正常的计算结不雅,或者异常情况。

    1. public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs) 
    2.  
    3. public static CompletableFuture<Object>  anyOf(CompletableFuture<?>... cfs) 

    例子如下:

    allOf办法是当所有的CompletableFuture都履行完后履行计算。

    anyOf办法是当随便率性一?CompletableFuture履行完后就会履行计算,计算的结不雅雷同。

    下面的代码运行结不雅有时是100,有时是"abc"。然则anyOf和applyToEither不合。anyOf接收随便率性多的CompletableFuture,然则applyToEither只是断定两个CompletableFuture。anyOf返回值的计算结不雅是参数中个一一个CompletableFuture的计算结不雅,applyToEither返回值的计算结不雅倒是要经由fn处理的。当然还有静态办法的差别,线程池的选择等。

    1. Random rand = new Random(); 
    2.  
    3. CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { 
    4.  
    5.     try { 
    6.  
    7.         Thread.sleep(10000 + rand.nextInt(1000)); 
    8.  
    9.     } catch (InterruptedException e) { 
    10.  
    11.         e.printStackTrace(); 
    12.  
    13.     } 
    14.  
    15.     return 100; 
    16.  
    17. }); 
    18.  
    19. CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { 
    20.  
    21.     try { 
    22.  
    23.         Thread.sleep(10000 + rand.nextInt(1000)); 
    24.  
    25.     } catch (InterruptedException e) { 
    26.  
    27.         e.printStackTrace(); 
    28.  
    29.     } 
    30.  
    31.     

        推荐阅读

        iOS中触摸事件的传递和响应机制

      【限时免费】岁尾最强一次云计算大年夜会,看传统、社区、互联网企业若何碰撞?【编辑推荐】2017 Android和iOS几回再三被曝Bug,它们都怎么了?谷歌苹不雅竟齐翻车!谈谈安卓8/iOS11那些BugiOS消息转发>>>详细阅读


      本文标题:Java CompletableFuture详解

      地址:http://www.17bianji.com/lsqh/40058.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)