CompletableFuture 大展身手(一)

一、CompletableFuture的源起

  在上一章我们提到了异步模式Future模式,但在实际生产过程中这个模式的会出现一些问题,我们来看以下代码:

ExecutorService service = Executors.newCachedThreadPool();
        //自定义任务1
        Future<String> fu1 = service.submit(()->{
            Thread.sleep(3000);
            return "mission 1 done";
        });
        //自定义任务二完成需要任务一先完成
        while(fu1.isDone()) {
        }
               Future<String> fu2 = service.submit(()->{
                Thread.sleep(3000);
                return "mission 2 done";
        });

  开始任务二的前提是任务一完成,所以只能在主线程加入while循环判断任务是否结束这种方式会浪费资源;如果使用get方法会阻塞当前线程,违背异步编程的理论,另外还有两个局限性:1、Future无法组合多个结果行成链式调用;2、没有异常处理。为了解决Future的局限性,在JDK1.8时引入了CompletableFuture。

二、CompletableFuture分析

public class CompletableFuture<T> implements Future<T>, CompletionStage<T>

Future在一片文章中讲过,这里介绍一个新面孔CompletionStage接口,这个接口主要提供多个方法便于我们将多个CompletionStage命令组合起来,从而满足实现多个命令的触发并且可以抛出异常。故将CompletionStage与Future结合与一身的Future就到了大展身手的时候了。

三、CompletableFuture常用方法

  1. CompletableFuture创建,一般有以下四种静态方法创建:
返回值 方法名 介绍
CompletableFuture<Void> runAsync(Runnable) 创建异步任务,使用默认线程池ForkJoinPool(这个详解在我的其他文章)
CompletableFuture<Void> runAsync(Runnable,Executor) 创建异步任务,使用指定线程池
CompletableFuture<U> supplyAsync(Supplier<U>) 与第一个相同,异同点此方法有返回值
CompletableFuture<U> supplyAsync(Supplier<U>,Executor) 与第二个相同,异同点此方法有返回值
  CompletableFuture<Void> future = CompletableFuture.runAsync(()->{
            System.out.println("hello");
        });
  CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "world";
        });
  future.get();
  System.out.println(future1.get());

上述例子采用默认线程池,runAsync和supplyAsync的区别就是第二个有返回值。

  1. 数据转换类方法
    2.1 thenApply方法
返回值 方法名 介绍
CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) 数据进行转换,使用ForkJoinPool线程池
CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn) 数据进行转换,使用ForkJoinPool线程池
CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor) 数据进行转换,自定义线程池
    CompletableFuture<String> future = CompletableFuture
                .supplyAsync(()->"hello")
                .thenApplyAsync(w->w + " world\n")
                .thenApplyAsync(w->w+" 真有意思\n")
                .thenApplyAsync(String::toUpperCase);
   System.out.println(future.get());

2.2 thenApply方法

返回值 方法名 介绍
CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) 转换CompletableFuture,使用ForkJoinPool线程池
CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) 转换CompletableFuture,使用ForkJoinPool线程池
CompletableFuture<U> thenComposeAsync( Function<? super T, ? extends CompletionStage<U>> fn,Executor executor) 转换CompletableFuture,自定义线程池
  CompletableFuture<String> future = CompletableFuture
                .supplyAsync(()->Thread.currentThread().getName()+"hello")
                .thenComposeAsync((w)->CompletableFuture.supplyAsync(()->w+"world"))
                .thenApply(String::toUpperCase);
  System.out.println(future.get());

上述可以看出thenApply将值进行串行处理,而thenComposeAsync将CompletableFuture进行处理。


  1. 组合
    3.1 thenAcceptBoth方法
返回值 方法名 介绍
CompletableFuture<Void> thenAcceptBoth(Function<? super T, ? extends CompletionStage<U>> fn) 结合传入的CompletableFuture,使用ForkJoinPool线程池
CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action) 结合传入的CompletableFuture,使用ForkJoinPool线程池
CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor) 结合传入的CompletableFuture,使用自定义线程池
  CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "hello";
        });
  CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "world";
        });
  future1.thenAcceptBoth(future,(a,b)->{System.out.println(b+a+"真有意思");});

结合传入的future,实现一个BiConsumer函数接口,从而实现将两个future结合起来。
3.2 thenCombine方法

返回值 方法名 介绍
CompletableFuture<U> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) 结合传入的CompletableFuture,使用ForkJoinPool线程池
CompletableFuture<U> thenCombineAsync( CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn 结合传入的CompletableFuture,使用ForkJoinPool线程池
CompletableFuture<U> thenCombineAsync( CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn, Executor executor 结合传入的CompletableFuture,使用自定义线程池
 CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            return "hello";
        });
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            return "world";
        });
CompletableFuture<String> test= future1
                .thenCombineAsync(future,(a,b)->{System.out.println(b+a+"真有意思");return "任务完成";});
System.out.println(test.get());

thenCombineAsync方法与thenAcceptBoth方法的区别为:

thenCombineAsync可以有一个CompletableFuture返回值;
thenCombineAsync第二个参数为BiFunction接口,thenAcceptBoth第二个参数为BiCosumer接口

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容

  • 思维笔的空性,我是一切的根源,意识里的种子迫使我看到发生的一切事物,今天感觉被受伤害的部分,都是因为我曾经去伤害过...
    湘羽瑶阅读 448评论 0 1
  • 什么是网络营销
    对待a阅读 146评论 0 0
  • 文/陈安若 出门吃午饭 路上遇故人 多年未相见 小聚相谈欢 往事重又提 再叹今日变 世道车轮滚 上下不同天
    陈安若阅读 193评论 9 5
  • 是在我休眠的时刻 伴随着 你唱了那支歌 你将忧劳沉入悠长江河 让我投入镜像的清波 阳光降临前的一刻 看见乌云翻涌而...
    半程风月阅读 776评论 6 2