前言

以前需要异步执行一个任务时,一般是用Thread或者线程池Executor去创建。如果需要返回值,则是调用Executor.submit获取Future。但是多个线程存在依赖组合,我们又能怎么办?可使用同步组件CountDownLatch、CyclicBarrier等;其实有简单的方法,就是用CompeletableFuture

  • 线程任务的创建
  • 线程任务的串行执行
  • 线程任务的并行执行
  • 处理任务结果和异常
  • 多任务的简单组合
  • 取消执行线程任务
  • 任务结果的获取和完成与否判断

关注公众号,一起交流,微信搜一搜: 潜行前行

1 创建异步线程任务

根据supplier创建CompletableFuture任务

//使用内置线程ForkJoinPool.commonPool(),根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
//指定自定义线程,根据supplier构建执行任务
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

根据runnable创建CompletableFuture任务

//使用内置线程ForkJoinPool.commonPool(),根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable)
//指定自定义线程,根据runnable构建执行任务
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
  • 使用示例
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> rFuture = CompletableFuture
.runAsync(() -> System.out.println("hello siting"), executor);
//supplyAsync的使用
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> {
System.out.print("hello ");
return "siting";
}, executor); //阻塞等待,runAsync 的future 无返回值,输出null
System.out.println(rFuture.join());
//阻塞等待
String name = future.join();
System.out.println(name);
executor.shutdown(); // 线程池需要关闭
--------输出结果--------
hello siting
null
hello siting

常量值作为CompletableFuture返回

//有时候是需要构建一个常量的CompletableFuture
public static <U> CompletableFuture<U> completedFuture(U value)

2 线程串行执行

任务完成则运行action,不关心上一个任务的结果,无返回值

public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
  • 使用示例
CompletableFuture<Void> future = CompletableFuture
.supplyAsync(() -> "hello siting", executor)
.thenRunAsync(() -> System.out.println("OK"), executor);
executor.shutdown();
--------输出结果--------
OK

任务完成则运行action,依赖上一个任务的结果,无返回值

public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
  • 使用示例
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
.supplyAsync(() -> "hello siting", executor)
.thenAcceptAsync(System.out::println, executor);
executor.shutdown();
--------输出结果--------
hello siting

任务完成则运行fn,依赖上一个任务的结果,有返回值

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)
  • 使用示例
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "hello world", executor)
.thenApplyAsync(data -> {
System.out.println(data); return "OK";
}, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello world
OK

thenCompose - 任务完成则运行fn,依赖上一个任务的结果,有返回值

  • 类似thenApply(区别是thenCompose的返回值是CompletionStage,thenApply则是返回 U),提供该方法为了和其他CompletableFuture任务更好地配套组合使用
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)
  • 使用示例
//第一个异步任务,常量任务
CompletableFuture<String> f = CompletableFuture.completedFuture("OK");
//第二个异步任务
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> "hello world", executor)
.thenComposeAsync(data -> {
System.out.println(data); return f; //使用第一个任务作为返回
}, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello world
OK

3 线程并行执行

两个CompletableFuture并行执行完,然后执行action,不依赖上两个任务的结果,无返回值

public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
  • 使用示例
//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
//第二个异步任务
.supplyAsync(() -> "hello siting", executor)
// () -> System.out.println("OK") 是第三个任务
.runAfterBothAsync(first, () -> System.out.println("OK"), executor);
executor.shutdown();
--------输出结果--------
OK

两个CompletableFuture并行执行完,然后执行action,依赖上两个任务的结果,无返回值

//第一个任务完成再运行other,fn再依赖消费两个任务的结果,无返回值
public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action)
//两个任务异步完成,fn再依赖消费两个任务的结果,无返回值
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action)
//两个任务异步完成(第二个任务用指定线程池执行),fn再依赖消费两个任务的结果,无返回值
public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action, Executor executor)
  • 使用示例
//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
//第二个异步任务
.supplyAsync(() -> "hello siting", executor)
// (w, s) -> System.out.println(s) 是第三个任务
.thenAcceptBothAsync(first, (s, w) -> System.out.println(s), executor);
executor.shutdown();
--------输出结果--------
hello siting

两个CompletableFuture并行执行完,然后执行action,依赖上两个任务的结果,有返回值

//第一个任务完成再运行other,fn再依赖消费两个任务的结果,有返回值
public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn)
//两个任务异步完成,fn再依赖消费两个任务的结果,有返回值
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn)
//两个任务异步完成(第二个任务用指定线程池执行),fn再依赖消费两个任务的结果,有返回值
public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn, Executor executor)
  • 使用示例
//第一个异步任务,常量任务
CompletableFuture<String> first = CompletableFuture.completedFuture("hello world");
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
//第二个异步任务
.supplyAsync(() -> "hello siting", executor)
// (w, s) -> System.out.println(s) 是第三个任务
.thenCombineAsync(first, (s, w) -> {
System.out.println(s);
return "OK";
}, executor);
System.out.println(future.join());
executor.shutdown();
--------输出结果--------
hello siting
OK

4 线程并行执行,谁先执行完则谁触发下一任务(二者选其最快)

上一个任务或者other任务完成, 运行action,不依赖前一任务的结果,无返回值

public CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action)
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action, Executor executor)
  • 使用示例
//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
try{ Thread.sleep(1000); }catch (Exception e){}
System.out.println("hello world");
return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
//第二个异步任务
.supplyAsync(() ->{
System.out.println("hello siting");
return "hello siting";
} , executor)
//() -> System.out.println("OK") 是第三个任务
.runAfterEitherAsync(first, () -> System.out.println("OK") , executor);
executor.shutdown();
--------输出结果--------
hello siting
OK

上一个任务或者other任务完成, 运行action,依赖最先完成任务的结果,无返回值

public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other,
Consumer<? super T> action)
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other,
Consumer<? super T> action, Executor executor)
public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other,
Consumer<? super T> action, Executor executor)
  • 使用示例
//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
try{ Thread.sleep(1000); }catch (Exception e){}
return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<Void> future = CompletableFuture
//第二个异步任务
.supplyAsync(() -> "hello siting", executor)
// data -> System.out.println(data) 是第三个任务
.acceptEitherAsync(first, data -> System.out.println(data) , executor);
executor.shutdown();
--------输出结果--------
hello siting

上一个任务或者other任务完成, 运行fn,依赖最先完成任务的结果,有返回值

public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other,
Function<? super T, U> fn)
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other,
Function<? super T, U> fn)
public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other,
Function<? super T, U> fn, Executor executor)
  • 使用示例
//第一个异步任务,休眠1秒,保证最晚执行晚
CompletableFuture<String> first = CompletableFuture.supplyAsync(()->{
try{ Thread.sleep(1000); }catch (Exception e){}
return "hello world";
});
ExecutorService executor = Executors.newSingleThreadExecutor();
CompletableFuture<String> future = CompletableFuture
//第二个异步任务
.supplyAsync(() -> "hello siting", executor)
// data -> System.out.println(data) 是第三个任务
.applyToEitherAsync(first, data -> {
System.out.println(data);
return "OK";
} , executor);
System.out.println(future);
executor.shutdown();
--------输出结果--------
hello siting
OK

5 处理任务结果或者异常

exceptionally-处理异常

public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
  • 如果之前的处理环节有异常问题,则会触发exceptionally的调用相当于 try...catch
  • 使用示例
CompletableFuture<Integer> first = CompletableFuture
.supplyAsync(() -> {
if (true) {
throw new RuntimeException("main error!");
}
return "hello world";
})
.thenApply(data -> 1)
.exceptionally(e -> {
e.printStackTrace(); // 异常捕捉处理,前面两个处理环节的日常都能捕获
return 0;
});

handle-任务完成或者异常时运行fn,返回值为fn的返回

  • 相比exceptionally而言,即可处理上一环节的异常也可以处理其正常返回值
public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn)
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn)
public <U> CompletableFuture<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,
Executor executor)
  • 使用示例
CompletableFuture<Integer> first = CompletableFuture
.supplyAsync(() -> {
if (true) { throw new RuntimeException("main error!"); }
return "hello world";
})
.thenApply(data -> 1)
.handleAsync((data,e) -> {
e.printStackTrace(); // 异常捕捉处理
return data;
});
System.out.println(first.join());
--------输出结果--------
java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
... 5 more
null

whenComplete-任务完成或者异常时运行action,有返回值

  • whenComplete与handle的区别在于,它不参与返回结果的处理,把它当成监听器即可
  • 即使异常被处理,在CompletableFuture外层,异常也会再次复现
  • 使用whenCompleteAsync时,返回结果则需要考虑多线程操作问题,毕竟会出现两个线程同时操作一个结果
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)
  • 使用示例
CompletableFuture<AtomicBoolean> first = CompletableFuture
.supplyAsync(() -> {
if (true) { throw new RuntimeException("main error!"); }
return "hello world";
})
.thenApply(data -> new AtomicBoolean(false))
.whenCompleteAsync((data,e) -> {
//异常捕捉处理, 但是异常还是会在外层复现
System.out.println(e.getMessage());
});
first.join();
--------输出结果--------
java.lang.RuntimeException: main error!
Exception in thread "main" java.util.concurrent.CompletionException: java.lang.RuntimeException: main error!
... 5 more

6 多个任务的简单组合

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)



  • 使用示例
 CompletableFuture<Void> future = CompletableFuture
.allOf(CompletableFuture.completedFuture("A"),
CompletableFuture.completedFuture("B"));
//全部任务都需要执行完
future.join();
CompletableFuture<Object> future2 = CompletableFuture
.anyOf(CompletableFuture.completedFuture("C"),
CompletableFuture.completedFuture("D"));
//其中一个任务行完即可
future2.join();

8 取消执行线程任务

// mayInterruptIfRunning 无影响;如果任务未完成,则返回异常
public boolean cancel(boolean mayInterruptIfRunning)
//任务是否取消
public boolean isCancelled()
  • 使用示例
CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> {
try { Thread.sleep(1000); } catch (Exception e) { }
return "hello world";
})
.thenApply(data -> 1); System.out.println("任务取消前:" + future.isCancelled());
// 如果任务未完成,则返回异常,需要对使用exceptionally,handle 对结果处理
future.cancel(true);
System.out.println("任务取消后:" + future.isCancelled());
future = future.exceptionally(e -> {
e.printStackTrace();
return 0;
});
System.out.println(future.join());
--------输出结果--------
任务取消前:false
任务取消后:true
java.util.concurrent.CancellationException
at java.util.concurrent.CompletableFuture.cancel(CompletableFuture.java:2276)
at Test.main(Test.java:25)
0

9 任务的获取和完成与否判断

// 任务是否执行完成
public boolean isDone()
//阻塞等待 获取返回值
public T join()
// 阻塞等待 获取返回值,区别是get需要返回受检异常
public T get()
//等待阻塞一段时间,并获取返回值
public T get(long timeout, TimeUnit unit)
//未完成则返回指定value
public T getNow(T valueIfAbsent)
//未完成,使用value作为任务执行的结果,任务结束。需要future.get获取
public boolean complete(T value)
//未完成,则是异常调用,返回异常结果,任务结束
public boolean completeExceptionally(Throwable ex)
//判断任务是否因发生异常结束的
public boolean isCompletedExceptionally()
//强制地将返回值设置为value,无论该之前任务是否完成;类似complete
public void obtrudeValue(T value)
//强制地让异常抛出,异常返回,无论该之前任务是否完成;类似completeExceptionally
public void obtrudeException(Throwable ex)
  • 使用示例
CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> {
try { Thread.sleep(1000); } catch (Exception e) { }
return "hello world";
})
.thenApply(data -> 1); System.out.println("任务完成前:" + future.isDone());
future.complete(10);
System.out.println("任务完成后:" + future.join());
--------输出结果--------
任务完成前:false
任务完成后:10

欢迎指正文中错误

基础篇:异步编程不会?我教你啊!CompeletableFuture的更多相关文章

  1. C#基础系列——异步编程初探:async和await

    前言:前面有篇从应用层面上面介绍了下多线程的几种用法,有博友就说到了async, await等新语法.确实,没有异步的多线程是单调的.乏味的,async和await是出现在C#5.0之后,它的出现给了 ...

  2. java基础篇---网络编程(TCP程序设计)

    TCP程序设计 在Java中使用Socket(即套接字)完成TCP程序的开发,使用此类可以方便的建立可靠地,双向的,持续的,点对点的通讯连接. 在Socket的程序开发中,服务器端使用serverSo ...

  3. java基础篇---网络编程(IP与URL)

    一:IP与InetAddress 在Java中支持网络通讯程序的开发,主要提供了两种通讯协议:TCP协议,UDP协议 可靠地连接传输,使用三方握手的方式完成通讯 不可靠的连接传输,传输的时候接受方不一 ...

  4. Scala基础篇-函数式编程的重要特性

    1.纯函数 表示函数无副作用(状态变化). 2.引用透明性 表示对相同输入,总是得到相同输出. 3.函数是一等公民 函数与变量.对象.类是同一等级.表示可以把函数当做参数传入另一个函数,或者作为函数的 ...

  5. java基础篇---网络编程(UDP程序设计)

    UDP程序设计 在TCP的索引操作都必须建立可靠地连接,这样一来肯定会浪费大量的系统性能,为了减少这种开销,在网络中又提供了另外一种传输协议---UDP,不可靠的连接,这种协议在各个聊天工具中被广泛的 ...

  6. Java 基础篇之编程基础

    基本数据类型 java 是强类型语言,在 java 中存储的数据都是有类型的,而且必须在编译时就确定其类型. 基本数据类型变量存储的是数据本身,而引用类型变量存的是数据的空间地址. 基本类型转换 自动 ...

  7. 温故知新,CSharp遇见异步编程(Async/Await),聊聊异步编程最佳做法

    什么是异步编程(Async/Await) Async/Await本质上是通过编译器实现的语法糖,它让我们能够轻松的写出简洁.易懂.易维护的异步代码. Async/Await是C# 5引入的关键字,用以 ...

  8. 深入浅出node(4) 异步编程

    一)函数式编程基础 二)异步编程的优势和难点 2.1 优势 2.2 难点 2.2.1 异常处理 2.2.2 函数嵌套过深 2.2.3 阻塞 2.2.4 多线程编程 2.2.5 异步转同步 三)异步编程 ...

  9. Promise和异步编程

    前面的话 JS有很多强大的功能,其中一个是它可以轻松地搞定异步编程.作为一门为Web而生的语言,它从一开始就需要能够响应异步的用户交互,如点击和按键操作等.Node.js用回调函数代替了事件,使异步编 ...

  10. 【读书笔记】【深入理解ES6】#11-Promise与异步编程

    异步编程的背景知识 JavaScript 引擎是基于单线程(Single-threaded)实际循环的概念构建的,同一时刻只允许一个代码块在执行. 所以需要跟踪即将运行的代码,那些代码被放在一个任务队 ...

随机推荐

  1. C语言经典100例-ex001

    系列文章<C语言经典100例>持续创作中,欢迎大家的关注和支持. 喜欢的同学记得点赞.转发.收藏哦- 后续C语言经典100例将会以pdf和代码的形式发放到公众号 欢迎关注:计算广告生态 即 ...

  2. linux的mysql数据库创建和删除

    mysql -h localhost -u 用戶名 -p密碼                //连接数据库use desk_show;                                 ...

  3. 配置交换机Trunk接口流量本地优先转发(集群/堆叠)

    组网图形 Eth-Trunk接口流量本地优先转发简介 在设备集群/堆叠情况下,为了保证流量的可靠传输,流量的出接口设置为Eth-Trunk接口.那么Eth-Trunk接口中必定存在跨框成员口.当集群/ ...

  4. layui的laypage实现分页/查询

    最开始我的数据绑定使用的razor语法来绑定的 就像下面这样 @if (ViewBag.listBlog != null) { foreach (var item in ViewBag.listBlo ...

  5. day89:luffy:使用Celery完成我的订单超时取消&Polyv视频加密播放

    目录 1.我的订单超时取消 2.PoliV视频播放 1.我的订单超时取消 使用Celery完成超时取消功能 mycelery/order/tasks.py from mycelery.main imp ...

  6. Spider--补充--Re模块_2

    # @ Author : Collin_PXY # Python 正则表达式的应用(二) # 正则表达式之所以让人头疼,很大程度是因为表达式里有大量的符号及它们的组合,还有很多匹配模式,想要记住比较困 ...

  7. 牛客网-声网2020校招-通用C++笔试题-2020.9.3

    1. 操作系统中两个进程争夺同一个资源会发生什么情况? 答:不一定死锁 解析:产生死锁的四个必要条件为 (1)互斥条件:一个资源每次只能被一个进程使用. (2)不可剥夺条件:进程已获得的资源,在未使用 ...

  8. IDEA 使用的一些快捷键记录

    1,ctrl+tab 导航当前编辑打开的所有文件,按住Ctrl,使用backspace 可以关闭某个文件 2,ctrl+shift+alt+s 打开项目设置,alt+shift+s 打开所有设置 3, ...

  9. Hadoop框架:MapReduce基本原理和入门案例

    本文源码:GitHub·点这里 || GitEE·点这里 一.MapReduce概述 1.基本概念 Hadoop核心组件之一:分布式计算的方案MapReduce,是一种编程模型,用于大规模数据集的并行 ...

  10. Weblogic CVE-2020-2551漏洞复现&CS实战利用

    Weblogic CVE-2020-2551漏洞复现 Weblogic IIOP 反序列化 漏洞原理 https://www.anquanke.com/post/id/199227#h3-7 http ...