基础篇:异步编程不会?我教你啊!CompletableFuture(JDK1.8)

前言

以前需要异步执行一个任务时,一般是用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.CancellationExceptionat 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

异步编程 CompletableFuture(JDK1.8)相关推荐

  1. 《Java8实战》读书笔记10:组合式异步编程 CompletableFuture

    <Java8实战>读书笔记10:组合式异步编程 CompletableFuture 第11章 CompletableFuture:组合式异步编程 11.1 Future 接口 (只是个引子 ...

  2. Java中如何使用非阻塞异步编程——CompletableFuture

    分享一波:程序员赚外快-必看的巅峰干货 对于Node开发者来说,非阻塞异步编程是他们引以为傲的地方.而在JDK8中,也引入了非阻塞异步编程的概念.所谓非阻塞异步编程,就是一种不需要等待返回结果的多线程 ...

  3. 【转载】Java 8 的异步编程 CompletableFuture

    文章目录 一个例子回顾 Future 一个例子走进CompletableFuture CompletableFuture使用场景 创建异步任务 supplyAsync方法 runAsync方法 任务异 ...

  4. java8 协程_Java8 异步编程—CompletableFuture

    Java 为并发编程提供了众多的工具,本文将重点介绍 Java8 中 CompletableFuture. 笔者在自己搜索资料及实践之后,避开已经存在的优秀文章的写作内容与思路,将以更加浅显的示例和语 ...

  5. 【并发编程】异步编程CompletableFuture实战

    文章目录 1.CompletableFuture简介 2.CompletableFuture核心API实战 3.CompletableFuture嵌套案例实战 4.合并两个CompletableFut ...

  6. java8 CompletableFuture异步编程

    Future 接口的局限性 Future接口可以构建异步应用,但依然有其局限性.它很难直接表述多个Future 结果之间的依赖性.实际开发中,我们经常需要达成以下目的: 将两个异步计算合并为一个--这 ...

  7. completable java_java8 CompletableFuture异步编程

    Future 接口的局限性 Future接口可以构建异步应用,但依然有其局限性.它很难直接表述多个Future 结果之间的依赖性.实际开发中,我们经常需要达成以下目的: 将两个异步计算合并为一个--这 ...

  8. JUC系列(十一) | Java 8 CompletableFuture 异步编程

    多线程一直Java开发中的难点,也是面试中的常客,趁着还有时间,打算巩固一下JUC方面知识,我想机会随处可见,但始终都是留给有准备的人的,希望我们都能加油!!! 沉下去,再浮上来,我想我们会变的不一样 ...

  9. 【异步编程学习笔记】JDK中的FutureTask和CompletableFuture详解(使用示例、源码)

    文章目录 FutureTask概述 使用实例 类图结构 FutureTask的run()方法 FutureTask的局限性 CompletableFuture概述 CompletableFuture代 ...

  10. Java8新的异步编程方式 CompletableFuture(三)

    前面两篇文章已经整理了CompletableFuture大部分的特性,本文会整理完CompletableFuture余下的特性,以及将它跟RxJava进行比较. 3.6 Either Either 表 ...

最新文章

  1. 转贴:雅虎公司C#笔试题,看看你能解答多少
  2. for循环递减_判断语句_循环语句
  3. python 获取打包后二进制所在目录
  4. centos修改SSH端口并禁用root远程登录
  5. NYOJ 76 超级台阶
  6. Java基类共同属性设置_多选择基类的访问属性-Java初学笔记
  7. 远控免杀专题2---msfvenom的隐藏参数
  8. python数据结构递归树_python数据结构(对称二叉树递归和迭代)
  9. python中math.log注意点
  10. 字符串专题 【2008】四1 C++版
  11. oracle注释 kole_t2u,oracle4
  12. java捕鱼达人源码_捕鱼达人java源码(完整功能)
  13. 八大排序之堆排序、快速排序、基数排序(java)。
  14. gpu版本pytorch配置
  15. 产品回顾本讲谈社汉字学习词典(kald)对于卡西欧EX-字的DataPlus系列
  16. 间隔层设备和过程层简介
  17. openFeign夺命连环9问,这谁受得了?
  18. 云日记个人中心项目思路
  19. Inspection info:Detects duplicates in source code
  20. SQL 中的LTRIM()和RTTIM()的用法

热门文章

  1. 获取基金数据python库_PYTHON爬取基金数据及基金筛选
  2. MAVEN打包时没有将src/main/cache文件夹打到到WAR包中
  3. 三分求单峰/单谷函数极值
  4. 【摘抄】为什么要学C语言
  5. html设置form居中,HTML中的表单Form实现居中效果
  6. 微信消息接口发送信息到分组和用户,错误代码40003和40008
  7. 使用433MHz RF模块制作一艘简易的Arduino遥控小船
  8. 苹果手机各种尺寸详细表以及iPhoneX、iPhoneXS、iPhoneXR、iPhoneXSMax、iPhone 11、iPhone 12、屏幕适配
  9. 使用Windows Live Writer WLW向Joomla网站发帖
  10. Java 使用嵌套 for 循环打印皇冠