作家
登录

Java CompletableFuture详解

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

它们与thenApply* 办法的差别在于handle*办法会处理正常计算值和异常,是以它可以樊篱异常,避免异常持续抛出。而thenApply*办法只是用来处理正常值,是以一旦有异常就会抛出。

纯花费结不雅

膳绫擎的办法是当计算完成的时刻,会生成新的计算结不雅(thenApply, handle),或者返回同样的计算结不雅(whenComplete,CompletableFuture)。CompletableFuture供给了一种处理结不雅的办法,只短卺不雅履行Action,而不返回新的计算值,是以计算值为Void:

看它的参数类型也就明白了,它们是花费型函数式接口Consumer,这个接口只有输入,没有返回值。

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<Void> f =  future.thenAccept(System.out::println); 
  8.  
  9. System.out.println(f.get()); 
  10.  
  11. public <U> CompletableFuture<Void>                thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action
  12.  
  13. public <U> CompletableFuture<Void>                thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action
  14.  
  15. public <U> CompletableFuture<Void>                thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor) 
  16.  
  17. public CompletableFuture<Void>  runAfterBoth(CompletionStage<?> other,  Runnable action

thenAcceptBoth以及相干办法供给了类似的功能,当两个CompletionStage都正常完成计算的时刻,就会履行供给的action,它用来组合别的一个异步的结不雅。

runAfterBoth是当两个CompletionStage都正常完成计算的时刻,履行一个Runnable,这个Runnable并不应用计算的结不雅。

更彻底地,下面一组办法当计算完成的时刻会履行一个Runnable,与thenAccept不合,Runnable并不应用CompletableFuture计算的结不雅。

  1. public CompletableFuture<Void>  thenRun(Runnable action
  2.  
  3. public CompletableFuture<Void>  thenRunAsync(Runnable action
  4.  
  5. public CompletableFuture<Void>  thenRunAsync(Runnable action,  Executor executor) 

是以先前的CompletableFuture计算的结不雅被忽视了,这个办法返回CompletableFuture<Void>类型的对象。

是以,你可以根据办法的参数的类型来加快你的记忆。Runnable类型的参数会忽视计算的结不雅,Consumer是纯花费计算结不雅,BiConsumer会组合别的一个CompletionStage纯花费,Function会对计算结不雅做转换,BiFunction会组合别的一个CompletionStage的计算结不雅做转换。

组合

有时,你须要在一个future构造运行某个函数,然则这个函数也是返回某种future,也就是说是两个future彼此依附串联在一路,它类似于flatMap。

  1. public <U> CompletableFuture<U>  thenCompose(Function<? super T,? extends CompletionStage<U>> fn) 

      推荐阅读

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

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


    本文标题:Java CompletableFuture详解

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

关键词: 探索发现

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

网友点评
自媒体专栏

评论

热度

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