CompletableFuture类总结)

2024-09-08 15:32
文章标签 总结 completablefuture

本文主要是介绍CompletableFuture类总结),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

CompletableFuture类总结


```java
public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {// 1、创建一个异步操作:无返回值public static CompletableFuture<Void> runAsync(Runnable runnable);public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);// 创建一个异步操作:有返回值public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);// 2、计算结果完成时的回调方法:异步线程执行完毕就执行public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)// 只有发生了异常才执行public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn);// 3、当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化。// T:上一个任务返回结果的类型// U:当前任务的返回值类型public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)    // 4、执行任务完成时对结果的处理。// handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);        // 5、接收任务的处理结果,并消费处理,无返回结果。public CompletionStage<Void> thenAccept(Consumer<? super T> action);public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);    // 6、跟 thenAccept 方法不一样的是,不关心任务的处理结果。只要上面的任务执行完成,就开始执行 thenAccept 。public CompletionStage<Void> thenRun(Runnable action);public CompletionStage<Void> thenRunAsync(Runnable action);public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);// 7、合并任务public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);// 8、当两个CompletionStage都执行完成后,把结果一块交给thenAcceptBoth来进行消费public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor);// 9、两个CompletionStage,谁执行返回的结果快,我就用那个CompletionStage的结果进行下一步的转化操作。public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);// 10、两个CompletionStage,谁执行返回的结果快,我就用那个CompletionStage的结果进行下一步的消耗操作。public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);// 11、两个CompletionStage,任何一个完成了都会执行下一步的操作(Runnable)public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);// 12、两个CompletionStage,都完成了计算才会执行下一步的操作(Runnable)public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);// 13、thenCompose 方法允许你对两个 CompletionStage 进行流水线操作,第一个操作完成时,将其结果作为参数传递给第二个操作。public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn) ;public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn, Executor executor);// 14、allOf 可以把多个任务都完成之后执行public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs);// 15、anyOf多个任务中有一个任务完成就执行:只有其中的一个值public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs);
}
示例```java
package com.qiqitrue.java.juc;import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;/*** @description:* @author: laiqi* @created: 2020-09-24 19:57*/
public class CompletableFutureExample {public static void main(String[] args) throws ExecutionException, InterruptedException {
//        handle();//        then();
//        runAfterBothAsync();
//        runAfterEitherAsync();allOf();}/*** 1、创建异步对象:无返回值的线程*/public static void runAsync() {System.out.println("主线程开始");CompletableFuture.runAsync(() -> {System.out.println("线程开始..");int a = 10 / 2;System.out.println("线程结束..");});System.out.println("主线程退出");}/*** 1、创建异步对象:有返回值的线程** @throws ExecutionException* @throws InterruptedException*/public static void supplyAsync() throws ExecutionException, InterruptedException {System.out.println("主线程开始");CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {System.out.println("线程开始..");int a = 10 / 2;System.out.println("线程结束..");return a;});Integer integer = completableFuture.get();System.out.println("主线程退出");}/*** 完成时回调执行:* 1、whenComplete:异步线程执行完毕就执行* 2、exceptionally:只有发生了异常才执行** @throws ExecutionException* @throws InterruptedException*/public static void whenComplete() throws ExecutionException, InterruptedException {System.out.println("主线程开始");CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {System.out.println("线程开始..");int a = 10 / 2;System.out.println("线程结束..");return a;}).whenComplete((integer, throwable) -> {System.out.println("我是whenComplete()方法:异步线程执行完毕之后就轮到我执行了,我可以获取返回值及异常信息,不能修改返回结果");}).exceptionally(throwable -> {System.out.println("我是exceptionally()方法:我只有在发生异常才会执行并返回出错时提供默认结果");return 0;});Integer integer = completableFuture.get();System.out.println("线程执行完毕返回值:" + integer);System.out.println("主线程退出");}/*** 完成时回调执行:* handle:* 当有异常时:whenComplete-->exceptionally-->handle* 当无异常时:whenComplete-->handle** @throws ExecutionException* @throws InterruptedException*/public static void handle() throws ExecutionException, InterruptedException {System.out.println("主线程开始");CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {System.out.println("线程开始..");int a = 10 / 2;System.out.println("线程结束..");return a;}).whenComplete((integer, throwable) -> {System.out.println("我是whenComplete()方法:异步线程执行完毕之后就轮到我执行了,我可以获取返回值及异常信息,不能修改返回结果");}).exceptionally(throwable -> {System.out.println("我是exceptionally()方法:我只有在发生异常才会执行并返回出错时提供默认结果");return 0;}).handle((integer, throwable) -> {System.out.println("我是handle()方法:我可以获取返回值及异常信息,并且可以修改返回结果");return 1;});Integer integer = completableFuture.get();System.out.println("线程执行完毕返回值:" + integer);System.out.println("主线程退出");}/*** 线程串行化* thenRunAsync:不可以接收前面的,自己不能有返回值* thenAcceptAsync:可以接收前面的返回值,自己不能有返回值* thenApplyAsync:可以接收前面的返回值,自己也需要返回值** @throws ExecutionException* @throws InterruptedException*/public static void then() throws ExecutionException, InterruptedException {String result = CompletableFuture.supplyAsync(() -> {System.out.println("线程A执行完毕");return "A";}).thenRunAsync(() -> {System.out.println("线程B执行完毕,我是没有返回值的");}).thenAcceptAsync(unused -> {System.out.println("线程C执行完毕,获取上个线程执行的返回值 = " + unused);}).thenApplyAsync(unused -> {System.out.println("线程D执行完毕,获取上个线程执行的返回值 = " + unused);return "D";}).thenApplyAsync(unused -> {System.out.println("线程E执行完毕,获取上个线程执行的返回值 = " + unused);return "E";}).get();System.out.println("result = " + result);}/*** 两任务组合-都要完成** @throws ExecutionException* @throws InterruptedException*/public static void runAfterBothAsync() throws ExecutionException, InterruptedException {// 异步任务一:返回1CompletableFuture<Integer> supplyAsync1 = CompletableFuture.supplyAsync(() -> {System.out.println("异步任务一");return 1;});// 异步任务二:返回2CompletableFuture<Integer> supplyAsync2 = CompletableFuture.supplyAsync(() -> {System.out.println("异步任务二");return 2;});//        // runAfterBothAsync:表示需要两个任务都执行完,才触发任务;但是不能接收前面任务的返回值,自己也不需要返回值
//        supplyAsync1.runAfterBothAsync(supplyAsync2, () -> {
//            System.out.println("runAfterBothAsync:需要异步任务一、异步任务二都执行之后我才执行;但是不能接收前面任务的返回值,自己也不需要返回值");
//        });// runAfterBothAsync:表示需要两个任务都执行完,才触发任务;可以接收前面任务的返回值,自己也不需要返回值
//        supplyAsync1.thenAcceptBothAsync(supplyAsync2, (integer, integer2) -> {
//            System.out.println("thenAcceptBothAsync:需要异步任务一、异步任务二都执行之后我才执行;可以接收前面任务的返回值,【任务一:"+integer+",任务二:"+integer2+"】,自己也不需要返回值");
//        });// thenCombineAsync:表示需要两个任务都执行完,才触发任务;可以接收前面任务的返回值,自己也需要返回值supplyAsync1.thenCombineAsync(supplyAsync2, (integer, integer2) -> {System.out.println("thenAcceptBothAsync:需要异步任务一、异步任务二都执行之后我才执行;可以接收前面任务的返回值,【任务一:" + integer + ",任务二:" + integer2 + "】,自己也不需要返回值");return integer + integer2;});}/*** 两任务组合-两个任务中有一个任务完成就执行** @throws ExecutionException* @throws InterruptedException*/public static void runAfterEitherAsync() throws ExecutionException, InterruptedException {// 异步任务一:返回1CompletableFuture<Integer> supplyAsync1 = CompletableFuture.supplyAsync(() -> {System.out.println("异步任务一");return 1;});// 异步任务二:返回2CompletableFuture<Integer> supplyAsync2 = CompletableFuture.supplyAsync(() -> {try {// 为了效果明显起见,增加下任务二慢点执行Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("异步任务二");return 2;});//        // runAfterEitherAsync:表示两个任务其一执行完就触发任务;但是不能接收前面任务的返回值,自己也不需要返回值
//        supplyAsync1.runAfterEitherAsync(supplyAsync2, () -> {
//            System.out.println("runAfterEitherAsync:需要异步任务一、异步任务二其中一个我就可以执行;但是不能接收前面任务的返回值,自己也不需要返回值");
//        });//        // acceptEitherAsync:表示两个任务其一执行完就触发任务;可以接收前面任务的返回值,自己也需要返回值
//        supplyAsync1.acceptEitherAsync(supplyAsync2, integer -> {
//            System.out.println("acceptEitherAsync:需要异步任务一、异步任务二其中一个我就可以执行;可以接收前面任务的返回值,自己也不需要返回值,前面值:" + integer);
//        });// applyToEitherAsync:表示两个任务其一执行完就触发任务;可以接收前面任务的返回值,自己也需要返回值supplyAsync1.applyToEitherAsync(supplyAsync2, integer -> {System.out.println("applyToEitherAsync:需要异步任务一、异步任务二其中一个我就可以执行;可以接收前面任务的返回值,自己也需要返回值,前面值:" + integer);return 1 + integer;});}/*** 多个任务全部都执行完* allOf:全部都执行* anyOf: 执行完任一个就行** @throws ExecutionException* @throws InterruptedException*/public static void allOf() throws ExecutionException, InterruptedException {CompletableFuture<String> supplyAsyncA = CompletableFuture.supplyAsync(() -> {System.out.println("异步任务一");return "A";});CompletableFuture<String> supplyAsyncB = CompletableFuture.supplyAsync(() -> {System.out.println("异步任务二");return "B";});CompletableFuture<String> supplyAsyncC = CompletableFuture.supplyAsync(() -> {System.out.println("异步任务三");return "C";});//        // allOf可以把多个任务都完成之后执行
//        final CompletableFuture<Void> allOf = CompletableFuture.allOf(supplyAsyncA, supplyAsyncB, supplyAsyncC);
//        // 阻塞等待
//        allOf.get();
//        System.out.println("异步任务一结果:" + supplyAsyncA.get());
//        System.out.println("异步任务二结果:" + supplyAsyncB.get());
//        System.out.println("异步任务三结果:" + supplyAsyncC.get());// anyOf多个任务中有一个任务完成就执行:只有其中的一个值final CompletableFuture<Object> anyOf = CompletableFuture.anyOf(supplyAsyncA, supplyAsyncB, supplyAsyncC);// 阻塞等待final Object rsult = anyOf.get();System.out.println("获取:" + rsult);}}

这篇关于CompletableFuture类总结)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1148483

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

二分最大匹配总结

HDU 2444  黑白染色 ,二分图判定 const int maxn = 208 ;vector<int> g[maxn] ;int n ;bool vis[maxn] ;int match[maxn] ;;int color[maxn] ;int setcolor(int u , int c){color[u] = c ;for(vector<int>::iter

整数Hash散列总结

方法:    step1  :线性探测  step2 散列   当 h(k)位置已经存储有元素的时候,依次探查(h(k)+i) mod S, i=1,2,3…,直到找到空的存储单元为止。其中,S为 数组长度。 HDU 1496   a*x1^2+b*x2^2+c*x3^2+d*x4^2=0 。 x在 [-100,100] 解的个数  const int MaxN = 3000

状态dp总结

zoj 3631  N 个数中选若干数和(只能选一次)<=M 的最大值 const int Max_N = 38 ;int a[1<<16] , b[1<<16] , x[Max_N] , e[Max_N] ;void GetNum(int g[] , int n , int s[] , int &m){ int i , j , t ;m = 0 ;for(i = 0 ;

go基础知识归纳总结

无缓冲的 channel 和有缓冲的 channel 的区别? 在 Go 语言中,channel 是用来在 goroutines 之间传递数据的主要机制。它们有两种类型:无缓冲的 channel 和有缓冲的 channel。 无缓冲的 channel 行为:无缓冲的 channel 是一种同步的通信方式,发送和接收必须同时发生。如果一个 goroutine 试图通过无缓冲 channel

9.8javaweb项目总结

1.主界面用户信息显示 登录成功后,将用户信息存储在记录在 localStorage中,然后进入界面之前通过js来渲染主界面 存储用户信息 将用户信息渲染在主界面上,并且头像设置跳转,到个人资料界面 这里数据库中还没有设置相关信息 2.模糊查找 检测输入框是否有变更,有的话调用方法,进行查找 发送检测请求,然后接收的时候设置最多显示四个类似的搜索结果

java面试常见问题之Hibernate总结

1  Hibernate的检索方式 Ø  导航对象图检索(根据已经加载的对象,导航到其他对象。) Ø  OID检索(按照对象的OID来检索对象。) Ø  HQL检索(使用面向对象的HQL查询语言。) Ø  QBC检索(使用QBC(Qurey By Criteria)API来检索对象。 QBC/QBE离线/在线) Ø  本地SQL检索(使用本地数据库的SQL查询语句。) 包括Hibern

暑期学习总结

iOS学习 前言无限轮播图换头像网络请求按钮的configuration属性总结 前言 经过暑期培训,完成了五个项目的仿写,在项目中将零散的内容经过实践学习,有了不少收获,因此来总结一下比较重要的内容。 无限轮播图 这是写项目的第一个难点,在很多项目中都有使用,越写越熟练。 原理为制造两个假页,在首和尾分别制作最后一页和第一页的假页,当移动到假页时,使用取消动画的方式跳到