作家
登录

Java CompletableFuture详解

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

  •  
  • CompletableFuture<String> f =  future.thenCombine(future2, (x,y) -> y + "-" + x); 
  •  
  • System.out.println(f.get()); //abc-100 
  • Either

    1. public CompletableFuture<Void>        acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action
    2.  
    3. public CompletableFuture<Void>        acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action
    4.  
    5. public CompletableFuture<Void>        acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) 
    6.  
    7. public <U> CompletableFuture<U>     applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn) 
    8.  
    9. public <U> CompletableFuture<U>     applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn) 
    10.  
    11. public <U> CompletableFuture<U>     applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn, Executor executor) 

    acceptEither办法是当随便率性一?CompletionStage完成的时刻,action这个花费者就会被履行。这个办法返回CompletableFuture<Void>

    applyToEither办法是当随便率性一?CompletionStage完成的时刻,fn会被履行,它的返回值会算作新的CompletableFuture<U>的计算结不雅。

    下面这个例子有时会输出100,有时刻会输出200,哪个Future先完成就会根据它的结不雅计算。

    1. Random rand = new Random(); 
    2.  
    3. CompletableFuture<Integer> future = 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<Integer> future2 = CompletableFuture.supplyAsync(() -> { 
    20.  
    21.     try { 
    22.  
    23.         Thread.sleep(10000 + rand.nextInt(1000)); 
    24.  
    25.     } catch (InterruptedException e) { 

    26.   推荐阅读

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

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


      本文标题:Java CompletableFuture详解

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

    关键词: 探索发现

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

    网友点评
    自媒体专栏

    评论

    热度

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