CompletableFuture API用法介绍(二)
文章目录
- 一、纯消费 API
- 1、thenAccep
- 2、thenAcceptBoth
- 3、runAfterBoth
- 4、thenRun(Runnable action)
- 二、组合API
- 1、thenCompose
- 2、thenCombine
- 三、acceptEither / applyToEither
- 1、 acceptEither
- 3、 applyToEither
- 四、allOf / anyOf
- 1、allOf
- 2、anyOf
上一篇文章介绍部分API CompletableFuture API用法介绍(一),这篇继续讲解CompletableFuture 其它API用法。
一、纯消费 API
单纯的去消费结果而不会返回新的值,因些计算结果为 Void;
1、thenAccep
- public CompletableFuture thenAccept(Consumer<? super T> action)
- public CompletableFuture thenAcceptAsync(Consumer<? super T> action)
- public CompletableFuture thenAcceptAsync(Consumer<? super T> action, Executor executor)】
public static void completableFuturThenAccep()throws Exception {CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> 10).thenAccept(System.out::println) //消费 上一级返回值 10.thenAcceptAsync(System.out::println); //上一级没有返回值 输出nullSystem.out.println(future.get());//null}
2、thenAcceptBoth
- public CompletableFuture thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
- public CompletableFuture thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
- public CompletableFuture thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor)
thenAccept 相比,参数类型多了一个 CompletionStage<? extends U> other,以上方法会接收上一个CompletionStage返回值,和当前的一个。
public static void complateFuturThenAcceptBoth() throws Exception {CompletableFuture.supplyAsync(() -> 10).thenAcceptBoth(CompletableFuture.supplyAsync(() -> 20), (a, b) -> {System.out.println(a);System.out.println(b);}).get();}
3、runAfterBoth
runAfterBoth 和以上方法不同,传一个 Runnable 类型的参数,不接收上一级的返回值
- public CompletableFuture runAfterBoth
- public CompletableFuture runAfterBothAsync
- public CompletableFuture runAfterBothAsync
public static void complateFuturRunAfterBoth() throws Exception { System.out.println("开始");CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {System.out.println(10);return 10;}).runAfterBoth(CompletableFuture.supplyAsync(() -> {System.out.println(20);return 20;}), () -> System.out.println("开始运行run"));System.out.println(future.get());}
4、thenRun(Runnable action)
thenRun它的入参是一个Runnable的实例,表示当得到上一步的结果时的操作。
- public CompletionStage thenRun(Runnable action);
- public CompletionStage thenRunAsync(Runnable action);
- public CompletionStage thenRunAsync(Runnable action,Executor executor);
public static void complateFuturThenRun() throws Exception {CompletableFuture.supplyAsync(() -> {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}return "hello";}).thenRun(() -> System.out.println("hello world"));while (true){}}
二、组合API
1、thenCompose
- public CompletableFuture thenCompose(Function<? super T,? extends CompletionStage> fn)
- public CompletableFuture thenComposeAsync(Function<? super T,? extends CompletionStage> fn)
- public CompletableFuture thenComposeAsync(Function<? super T,? extends CompletionStage> fn, Executor executor)
以上接收类型为 Function<? super T,? extends CompletionStage> fn ,fn 接收上一级返回的结果,并返回一个新的 CompletableFuture
public static void complateFuturThenCompose() throws Exception {CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 1).thenApply((a) -> {try {Thread.sleep(1000);} catch (InterruptedException e) {}return a + 10;}).thenCompose((s) -> {System.out.println(s); //11return CompletableFuture.supplyAsync(() -> s * 5);});System.out.println(future.get());//55}
}
2、thenCombine
- public <U,V> CompletableFuture thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
- public <U,V> CompletableFuture thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
- public <U,V> CompletableFuture thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor)
两个CompletionStage是并行执行的,它们之间并没有先后依赖顺序,other并不会等待先前的CompletableFuture执行完毕后再执行。
thenCombine 和 supplyAsync 不一定哪个先哪个后,是并行执行的。
public static void complateFuturThenCombine() throws Exception {Random random = new Random();CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("supplyAsync");return 2;}).thenApply((a) -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("thenApply");return a * 3;}).thenCombine(CompletableFuture.supplyAsync(() -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println("thenCombineAsync");return 10;}), (a, b) -> {System.out.println(a);System.out.println(b);return a + b;});System.out.println(future.get());}
三、acceptEither / applyToEither
1、 acceptEither
- public CompletableFuture acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
- public CompletableFuture acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)
- public CompletableFuture acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)
acceptEither方法是当任意一个 CompletionStage 完成的时候,action 这个消费者就会被执行。这个方法返回 CompletableFuture
public static void complateFuturAcceptEither() throws Exception {Random random = new Random();CompletableFuture.supplyAsync(() -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}return "A";}).acceptEither(CompletableFuture.supplyAsync(() -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}return "B";}), System.out::println).get();}
以上代码有时输出A,有时输出B,哪个Future先执行完就会根据它的结果计算。
3、 applyToEither
总会碰到有两种渠道完成同一个事情,所以就可以调用这个方法,找一个最快的结果进行处理。
- public CompletionStage applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
- public CompletionStage applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
- public CompletionStage applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);
public static void complateFuturApplyToEitherr() throws Exception {String result = CompletableFuture.supplyAsync(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}return "s1";}).applyToEither(CompletableFuture.supplyAsync(() -> {try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}return "hello world";}), s -> s).join();System.out.println(result);}
acceptEither 没有返回值,applyToEither 有返回值
四、allOf / anyOf
1、allOf
- public static CompletableFuture allOf
这个方法的意思是把有方法都执行完才往下执行,没有返回值
public static void complateFuturAllOf() throws Exception {Random random = new Random();CompletableFuture.allOf(CompletableFuture.runAsync(() -> {try {Thread.sleep(random.nextInt(5000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println(1);}),CompletableFuture.runAsync(() -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println(2);})).get();}
2、anyOf
- public static CompletableFuture anyOf(CompletableFuture<?>… cfs)
任务一个方法执行完都往下执行,返回一个Object类型的值
public static void complateFuturAnyOf() throws Exception {Random random = new Random();Object o = CompletableFuture.anyOf(CompletableFuture.runAsync(() -> {try {Thread.sleep(random.nextInt(4000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println(1);}),CompletableFuture.runAsync(() -> {try {Thread.sleep(random.nextInt(1000));} catch (InterruptedException e) {e.printStackTrace();}System.out.println(2);})).get();System.out.println(o);}
以上就是CompletableFuture API的基本用法,根据业务灵活组合使用。对我们的编程会很有帮助。
CompletableFuture API用法介绍(二)相关推荐
- CompletableFuture API用法介绍(一)
文章目录 一.前言 二.CompletableFuture 1.主动完成计算 2.创建异步任务 3.计算完成时对结果的处理 whenComplete/exceptionally/handle 4.结果 ...
- Python Pillow(PIL)库的用法介绍(二)
Python Pillow(PIL)库的用法介绍(二) 在上一篇文章中介绍了Pillow库的一些基本用法,参考:https://blog.csdn.net/weixin_43790276/articl ...
- Scanpy(一)AnnData数据结构与一些API用法介绍
目录 Scanpy简介与安装 AnnData AnnData的结构 h5ad:AnnData的写入和读取 Scanpy中一些常用api的用法介绍 sc.pp.filter_cells sc.pp.fi ...
- pm2常用的命令用法介绍
pm2 是一个带有负载均衡功能的Node应用的进程管理器.当你要把你的独立代码利用全部的服务器上的所有CPU,并保证进程永远都活着,0秒的重载, PM2是完美的,下面我们来看pm2常用的命令用法介绍吧 ...
- c语言组json包,json格式解析和libjson的用法介绍(关于cjson的使用方法)
在阅读本文之前,请先阅读下<Rss Reader实例开发之系统设计>一文. Rss Reader实例开发中,进行网络数据交换时主要使用到了两种数据格式:JSON与XML.本文主要介绍JSO ...
- Junit和Junit.Jupiter.api用法区别
Junit和Junit.Jupiter.api用法区别写在了文章的总结处,这里先简单的介绍一下Junit用法. Junit 5 = Junit Platform + Junit Jupiter + J ...
- 强大的 API 监控工具 之 Win32Exts for API Monitor 介绍
强大的 API 监控工具 之 Win32Exts for API Monitor 介绍 Win32Exts for API_Monitor 是Win32Exts项目组提供的一个强大的 ...
- awk 和sed的用法介绍
awk 和sed的用法介绍 一.awk的介绍 1. 作用及用法要求 2. 使用方法 (1)使用的命令: (2)举例说明: 二.sed的介绍 1. 用法介绍及常用命令 2. 具体使用 一.awk的介绍 ...
- 什么是mysql的游标_MySQL游标概念是什么 MySQL游标概念与用法介绍
本篇文章小编给大家分享一下MySQL游标概念与用法介绍,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. 1.游标的概念(Cursor) 一条sql,对应N条资源,取出资源的接 ...
最新文章
- linux删除新建的磁盘分区,Fixmbr,删除磁盘分区,新建磁盘分区,等待正式Ubuntu...
- 面试题之在字符串中查找出第一个只出现一次的字符的位置
- 安装vmware 6.52 Red Hat Enterprise Linux 5(rhel-5.1-server-i386-dvd) openldap2.4
- Mybatis配置文件注释
- php index.php 文件路径,自研 PHP 框架 1.0_index.php 文件说明
- 图片大_2020跨年图片 元旦快乐祝福图片 2019再见2020你好图片大全 新年图片
- python程序运行原理_谈谈 Python 程序的运行原理
- [深度学习-优化]欠拟合与过拟合以及解决方法
- Android -- 重置Bitmap大小Bitmap转角度
- 解决Mac文件乱码问题
- mysql sqlite 语法_浅谈sqlite与mysql的数据库语法差异_沃航科技
- Android Camera 测光梳理
- 人生辣么多的谎言,没必要一个个试一下
- android 添加子view,如何在Android中向ImageView添加子视图
- java字体被背景盖住_背景透明后字体,贴图产生遮盖覆盖问题的解决方法。
- css中a标签中去掉下划线注意事项
- HTC使用官方固件作为底包制作rom卡刷包教程
- Java使用百度地图API,根据地址,查询地址坐标。
- 聊一聊龙蜥硬件兼容性 SIG 那些事儿 | 龙蜥 SIG
- 服务器连接网页被迫下线,“对不起 您的网络连接不稳定 您的账号已被迫下线”的原因分析及解决方法...
热门文章
- Linux要学git吗,git学习一 基于linux ubuntu git安装与配置
- timerpickerview使用_详解iOS App中UIPickerView滚动选择栏的添加方法
- 英语语法---从句总结
- 英语语法---名词详解
- INTERSPEECH 2021 AutoSpeech挑战赛开启报名
- javascript精要(3)-动态加载脚本
- c++17(17)-异常try catch,operator[],vector at
- 【CV】给AI一张高清照片,分分钟还你细节满满的3D人体模型,GitHub标星4.4k | 在线可玩...
- 【机器学习基础】机器学习中“距离与相似度”计算汇总
- Github标星86.4K+:常见数据结构与算法的Python实现