一、简介

 所谓异步调用其实就是实现一个无需等待被调用函数的返回值而让操作继续运行的方法。在 Java 语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需要等待计算结果。但调用者仍需要取线程的计算结果。

 JDK5新增了 Future 接口,用于描述一个异步计算的结果。虽然 Future 以及相关使用方法提供了异步执行任务的能力,但是对于结果的获取却是很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然和我们的异步编程的初衷相违背,轮询的方式又会耗费无谓的 CPU 资源,而且也不能及时地得到计算结果。

private static final ExecutorService POOL = Executors.newFixedThreadPool(TASK_THRESHOLD, new ThreadFactory() {
AtomicInteger atomicInteger = new AtomicInteger(0); @Override
public Thread newThread(Runnable r) {
return new Thread(r, "demo15-" + atomicInteger.incrementAndGet());
}
}); public static void main(String[] args) throws ExecutionException, InterruptedException {
Future<Integer> submit = POOL.submit(() -> 123);
// 1. get() 方法用户返回计算结果,如果计算还没有完成,则在get的时候会进行阻塞,直到获取到结果为止
Integer get = submit.get();
// 2. isDone() 方法用于判断当前Future是否执行完成。
boolean done = submit.isDone();
// 3. cancel(boolean mayInterruptIfRunning) 取消当前线程的执行。参数表示是否在线程执行的过程中阻断。
boolean cancel = submit.cancel(true);
// 4. isCancelled() 判断当前task是否被取消.
boolean cancelled = submit.isCancelled();
// 5. invokeAll 批量执行任务
Callable<String> callable = () -> "Hello Future";
List<Callable<String>> callables = Lists.newArrayList(callable, callable, callable, callable);
List<Future<String>> futures = POOL.invokeAll(callables);
}

 在Java8中,CompletableFuture 提供了非常强大的 Future 的扩展功能,可以帮助我们简化异步编程的复杂性,并且提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合 CompletableFuture 的方法。

tips: CompletionStage 代表异步计算过程中的某一个阶段,一个阶段完成以后可能会触发另外一个阶段。

二、CompletableFuture 使用

1. runAsync、supplyAsync

// 无返回值
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)

runAsync、supplyAsync 方法是 CompletableFuture 提供的创建异步操作的方法。需要注意的是,如果没有指定 Executor 作为线程池,将会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码;如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同。

public class Demo1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> runAsync = CompletableFuture.runAsync(() -> System.out.println(123)); CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> "CompletableFuture");
System.out.println(supplyAsync.get());
}
}

### 2. whenComplete、exceptionally
```java
// 执行完成时,当前任务的线程执行继续执行 whenComplete 的任务。
public CompletableFuture whenComplete(BiConsumer action)
// 执行完成时,把 whenCompleteAsync 这个任务提交给线程池来进行执行。
public CompletableFuture whenCompleteAsync(BiConsumer action)
public CompletableFuture whenCompleteAsync(BiConsumer action, Executor executor)
public CompletableFuture exceptionally(Function fn)
```
当 CompletableFuture 的计算完成时,会执行 whenComplete 方法;当 CompletableFuture 计算中抛出异常时,会执行 exceptionally 方法。
```java
public class Demo2 {

public static void main(String[] args) throws ExecutionException, InterruptedException {

    CompletableFuture<Integer> runAsync = CompletableFuture.supplyAsync(() -> 123456);
runAsync.whenComplete((t, throwable) -> {
System.out.println(t);
if (throwable != null) {
throwable.printStackTrace();
}
});
runAsync.whenCompleteAsync((t, throwable) -> {
System.out.println(t);
if (throwable != null) {
throwable.printStackTrace();
}
});
runAsync.exceptionally((throwable) -> {
if (throwable != null) {
throwable.printStackTrace();
}
return null;
});
TimeUnit.SECONDS.sleep(2);
}

}

<br/>
### 3. thenApply、handle
```java
// 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) 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);

当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化

handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行,还可以处理异常的任务。thenApply 只可以执行正常的任务,任务出现异常则不执行 thenApply 方法。

public class Demo3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
// thenApply
CompletableFuture<Integer> thenApply = CompletableFuture.supplyAsync(() -> 123).thenApply(t -> t * t);
System.out.println(thenApply.get()); // handle
CompletableFuture<Integer> handle = CompletableFuture.supplyAsync(() -> {
int i = 10 / 0;
return new Random().nextInt(10);
}).handle((t, throwable) -> {
if (throwable != null) {
throwable.printStackTrace();
return -1;
}
return t * t;
});
System.out.println(handle.get());
}
}

### 4. thenAccept、thenRun
```java
public CompletionStage thenAccept(Consumer action);
public CompletionStage thenAcceptAsync(Consumer action);
public CompletionStage thenAcceptAsync(Consumer action,Executor executor);

public CompletionStage thenRun(Runnable action);

public CompletionStage thenRunAsync(Runnable action);

public CompletionStage thenRunAsync(Runnable action,Executor executor);

thenAccept  接收任务的处理结果,并消费处理。无返回结果。

thenRun 跟 thenAccept 方法不一样的是,不关心任务的处理结果。只要上面的任务执行完成,就开始执行 thenRun。
```java
public class Demo4 { public static void main(String[] args) {
// thenAccept
CompletableFuture<Void> thenAccept = CompletableFuture.supplyAsync(() -> new Random().nextInt(10)).thenAccept(System.out::println); // thenRun
CompletableFuture<Void> thenRun = CompletableFuture.supplyAsync(() -> new Random().nextInt(10)).thenRun(() -> System.out.println(123));
}
}

### 5. thenCombine、thenAcceptBoth
```java
// T 表示第一个 CompletionStage 的返回结果类型
// U 表示第二个 CompletionStage 的返回结果类型
// V表示 thenCombine/thenAcceptBoth 处理结果类型
public CompletionStage thenCombine(CompletionStage other,BiFunction fn);
public CompletionStage thenCombineAsync(CompletionStage other,BiFunction fn);
public CompletionStage thenCombineAsync(CompletionStage other,BiFunction fn,Executor executor);

public <U,V> CompletionStage thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);

public <U,V> CompletionStage thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);

public <U,V> CompletionStage thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);

thenCombine、thenAcceptBoth 都是用来合并任务 —— 等待两个 CompletionStage 的任务都执行完成后,把两个任务的结果一并来处理。区别在于 thenCombine 有返回值;thenAcceptBoth 无返回值。
```java
public class Demo5 { public static void main(String[] args) throws ExecutionException, InterruptedException {
// thenCombine
CompletableFuture<String> thenCombine = CompletableFuture.supplyAsync(() -> new Random().nextInt(10))
.thenCombine(CompletableFuture.supplyAsync(() -> "str"),
// 第一个参数是第一个 CompletionStage 的处理结果
// 第二个参数是第二个 CompletionStage 的处理结果
(i, s) -> i + s
);
System.out.println(thenCombine.get()); // thenAcceptBoth
CompletableFuture<Void> thenAcceptBoth = CompletableFuture.supplyAsync(() -> new Random().nextInt(10))
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> "str"),
(i, s) -> System.out.println(i + s));
}
}

### 6. applyToEither、acceptEither、runAfterEither、runAfterBoth
- applyToEither:两个 CompletionStage,谁执行返回的结果快,就用那个 CompletionStage 的结果进行下一步的处理,有返回值。
- acceptEither:两个 CompletionStage,谁执行返回的结果快,就用那个 CompletionStage 的结果进行下一步的处理,无返回值。
- runAfterEither:两个 CompletionStage,任何一个完成了,都会执行下一步的操作(Runnable),无返回值。
- runAfterBoth:两个 CompletionStage,都完成了计算才会执行下一步的操作(Runnable),无返回值。

由于这几个方法含义相近,使用更加类似,我们就以 applyToEither 来介绍...

// T 两个 CompletionStage 组合运算后的结果类型
// U 下一步处理运算的结果返回值类型
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);
public class Demo6 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Integer> applyToEither = CompletableFuture.supplyAsync(() -> {
int nextInt = new Random().nextInt(10);
try {
Thread.sleep(nextInt);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1=" + nextInt);
return nextInt;
}).applyToEither(CompletableFuture.supplyAsync(() -> {
int nextInt = new Random().nextInt(10);
try {
Thread.sleep(nextInt);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2=" + nextInt);
return nextInt;
}), i -> i); System.out.println(applyToEither.get());
}
}

### 7. thenCompose
```java
public CompletableFuture thenCompose(Function> fn);
public CompletableFuture thenComposeAsync(Function> fn) ;
public CompletableFuture thenComposeAsync(Function> fn, Executor executor) ;
```
thenCompose 方法允许你对两个 CompletionStage 进行流水线操作,第一个操作完成时,将其结果作为参数传递给第二个操作。
```java
public class Demo7 {

public static void main(String[] args) throws ExecutionException, InterruptedException {

    CompletableFuture<Integer> thenCompose = CompletableFuture.supplyAsync(() -> new Random().nextInt(10))
.thenCompose(i -> CompletableFuture.supplyAsync(() -> i * i));
System.out.println(thenCompose.get()); }

}

<br/>
参考博文:[https://www.jianshu.com/p/6bac52527ca4](https://www.jianshu.com/p/6bac52527ca4)

Java8 CompletableFuture 编程的更多相关文章

  1. 关于Java8函数式编程你需要了解的几点

    函数式编程与面向对象的设计方法在思路和手段上都各有千秋,在这里,我将简要介绍一下函数式编程与面向对象相比的一些特点和差异. 函数作为一等公民 在理解函数作为一等公民这句话时,让我们先来看一下一种非常常 ...

  2. Java8 函数式编程详解

    Java8 函数式编程详解 Author:Dorae Date:2017年11月1日23:03:26 转载请注明出处 说起Java8,可能很多人都已经知道其最大的改进,就是引入了Lambda表达式与S ...

  3. Java8函数式编程探秘

    引子 将行为作为数据传递 怎样在一行代码里同时计算一个列表的和.最大值.最小值.平均值.元素个数.奇偶分组.指数.排序呢? 答案是思维反转!将行为作为数据传递. 文艺青年的代码如下所示: public ...

  4. [2017.02.23] Java8 函数式编程

    以前学过Haskell,前几天又复习了其中的部分内容. 函数式编程与命令式编程有着不一样的地方,函数式编程中函数是第一等公民,通过使用少量的几个数据结构如list.map.set,以及在这些数据结构上 ...

  5. Java8 CompletableFuture组合式的编程(笔记)

    * 实现异步API public double getPrice(String product) { return calculatePrice(product); } /** * 同步计算商品价格的 ...

  6. [一] java8 函数式编程入门 什么是函数式编程 函数接口概念 流和收集器基本概念

      本文是针对于java8引入函数式编程概念以及stream流相关的一些简单介绍 什么是函数式编程?   java程序员第一反应可能会理解成类的成员方法一类的东西 此处并不是这个含义,更接近是数学上的 ...

  7. Java8 CompletableFuture

    http://colobu.com/2016/02/29/Java-CompletableFuture/ http://www.deadcoderising.com/java8-writing-asy ...

  8. Java8函数式编程学习笔记(初探)

    编程语言的整个目的就在于操作值,要是按照历史上编程语言的传统,这些值被成为一等值,而编程语言中的其他结构也许有助于表示值的结构,但在程序执行期间不能传递,因此为二等值,比如方法和类等则是二等值,类可以 ...

  9. 漫漫人生路,学点Jakarta基础-Java8函数式编程

    接口默认方法 Java8版本以后新增了接口的默认方法,不仅仅只能包含抽象方法,接口也可以包含若干个实例方法.在接口内定义实例方法(但是注意需要使用default关键字) 在此定义的方法并非抽象方法,而 ...

随机推荐

  1. 深入理解Java的switch...case...语句

    switch...case...中条件表达式的演进 最早时,只支持int.char.byte.short这样的整型的基本类型或对应的包装类型Integer.Character.Byte.Short常量 ...

  2. APP系统架构设计初探

    一,图片体验的优化. 在手机上显示图片,速度是一个非常重要的体验点,试想,如果您打开一个网站,发现里面的图片一直显示失败或者是x,稍微做得好一点的,可能是一个不消失的loading或者是菊花等等,但不 ...

  3. 如何编写无须人工干预的shell脚本

    在使用基本的一些shell命令时,机器需要与人进行互动来确定命令的执行.比如 cp test.txt boo/test.txt,会询问是否覆盖?ssh远程登陆时,需要输入人工密码后,才可以继续执行ss ...

  4. 7.30考试password

    先说地球人都看得出来的,该数列所有数都是p的斐波那契数列中所对应的数的次幂,所以一开始都以为是道水题,然而斐波那契数列增长很快,92以后就爆long long ,所以要另谋出路,于是乎向Ren_iva ...

  5. Spring Cloud使用Zuul网关时报错

    当开启了Eureka集群后,每创建一个服务都要往这两个集群中进行注册否则访问时会产生500

  6. MFC在一个工程中启动其他工程的exe文件

    说明:有的时候把两个工程合并,但是偷懒不想在工程中添加代码,所以想到了这个办法,仅限偷懒哈哈哈哈 方法:新建一个主程序,在主程序的界面中添加按钮,在按钮的程序代码中添加以下语句: void CMain ...

  7. Spring 核心技术(4)

    接上篇:Spring 核心技术(3) version 5.1.8.RELEASE 1.4.2 依赖关系及配置详情 如上一节所述,你可以将 bean 属性和构造函数参数定义为对其他托管 bean(协作者 ...

  8. 微信小程序踩坑日记1——调用微信授权窗口

    0. 引言 微信小程序为了优化用户体验,取消了在进入小程序时立马出现授权窗口.需要用户主动点击按钮,触发授权窗口. 那么,在我实践过程中,出现了以下问题. . 无法弹出授权窗口 . 希望在用户已经授权 ...

  9. C# Socket服务器端如何判断客户端断开求解

    Socket client //假如已经创建好了,连接到服务器端得Socket的客户端对象. 我们只要client.Poll(10,SelectMode.SelectRead)判断就行了.只要返回Tr ...

  10. C/C++用new、delete分配回收堆中空间

    int *CreateList() 10 { 11 int a[5]; 12 int *a = new int[5]; 13 delete[] a; 14 15 int a(5); 16 int a ...