前言

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

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

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 线程串行执行

image

任务完成则运行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 线程并行执行,合并两任务

image

两个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 线程并行执行,谁先执行完则谁触发下一任务(二者选其最快)

image

上一个任务或者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-处理异常

image

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)
image

image

  • 使用示例
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

作者:cscw0521
原文链接:https://blog.csdn.net/u013591094/article/details/110682973


http://www.taodudu.cc/news/show-2402146.html

相关文章:

  • String类
  • 一些区别的说明
  • box-sizing属性的content-box值和border-box值的区别
  • IBM SPSS Statistics频数分析教学
  • Pr 音频效果参考:调制
  • Pr播放视频没声音,音频硬件显示不工作怎么办?
  • PR音频处理——音乐逐渐萎靡的效果
  • PR 音频去噪、音频信号增强、音频导出wav文件;
  • PR音频处理——收尾音乐
  • 【PR】音频处理
  • pr音频效果特效
  • 【7】PR音频及结合AU去除噪音【8】PR字幕运用
  • Pr:音频剪辑混合器和音轨混合器
  • Pr 音频效果参考:滤波器与 EQ
  • Pr 音频效果参考:延迟与回声
  • Pr 音频效果参考:立体声声像、时间与变调
  • Pr:音频轨道
  • pr字幕音频
  • PR音频优化
  • Pr 与音频相关的调整方法
  • VMWare IOS MAC分区教程
  • mac磁盘分区管理
  • Mac电脑删除某个分区
  • 安装的Mac Windows双系统,Mac分区的空间太小/太大了,有什么办法调整吗?
  • Mac分区合并
  • 如何解决--Mac的磁盘工具无法对移动硬盘分区,分区按钮是灰色的?
  • Mac book 合并分区,报错文件系统验证失败的解决办法
  • Mac没有winnt格式_Mac磁盘到底要不要分区?
  • mac 磁盘分区 diskutil命令
  • kafka 修改分区_kafka分区

异步编程不会?我教你啊!CompletableFuture(JDK1.8)相关推荐

  1. java 并发 异步_Java并发 CompletableFuture异步编程的实现

    前面我们不止一次提到,用多线程优化性能,其实不过就是将串行操作变成并行操作.如果仔细观察,你还会发现在串行转换成并行的过程中,一定会涉及到异步化,例如下面的示例代码,现在是串行的,为了提升性能,我们得 ...

  2. 【Java并发编程实战】(十七):Future和CompletableFuture的原理及实战——异步编程没有那么难

    文章目录 引言 生活中的例子 场景1 场景2 Java中的Future 如何获取Future Future的主要方法及使用 Future的核心源码 Future模式的高阶版本-- Completabl ...

  3. java 异步_浅谈Java异步编程

    本文来自网易云社区. Java异步编程引言 Java的异步编程其实是一个充分利用计算机CPU资源,不想让主程序阻塞在某个长时间运行的任务上,这类耗时的任务可以是IO操作.远程调用以及高密度计算任务.如 ...

  4. 今天,我要教妹子学会Spring:Aware、异步编程、计划任务

    来源 | 沉默王二 教妹子学 Spring,没见过这么放肆的标题吧? 作者我有一个漂亮如花的妹妹(见封面图,别问我怎么又变了?还不能一天做个梦了?),她叫什么呢?我想聪明的读者能猜得出:沉默王三,没错 ...

  5. python twisted教程一,异步编程

    前言 最近有人在twisted邮件列表中问有没有一个可以让人快速学习twisted的文档.总体的来说:这个系列不是这样的一个文档.如果你没有很多时间或者耐心的话,这个系列的文章不太适合你. 不过,如果 ...

  6. Java 8 的异步编程利器 CompletableFuture 真香!

    大家好,我是不才陈某~ 最近刚好使用CompeletableFuture优化了项目中的代码,所以跟大家一起学习CompletableFuture. 一个例子回顾 Future 因为Completabl ...

  7. JS 异步编程的 5 种解决方案

    我们知道 JS 语言的执行环境是"单线程",所谓"单线程",就是指一次只能完成一件任务,这种模式的好处是实现起来比较简单,执行环境相对单纯:坏处是只要有一个任务 ...

  8. 第一章: Vert.x 异步编程的基础知识

    第一章: Vert.x 异步编程的基础知识 翻译: 白石(https://github.com/wjw465150/Vert.x-Core-Manual) 构建反应式系统的第一步是采用异步编程.基于阻 ...

  9. 【C++】多线程与异步编程【四】

    文章目录 [C++]多线程与异步编程[四] 0.三问 1.什么是异步编程? 1.1同步与异步 1.2 **阻塞与非阻塞** 2.如何使用异步编程 2.1 使用全局变量与条件变量传递结果 实例1: 2. ...

  10. Python网络编程(4)——异步编程select epoll

    在SocketServer模块的学习中,我们了解了多线程和多进程简单Server的实现,使用多线程.多进程技术的服务端为每一个新的client连接创建一个新的进/线程,当client数量较多时,这种技 ...

最新文章

  1. ADAS感知算法观察
  2. 1SGD、Momention原理
  3. MySQL5.7 group by新特性,报错1055
  4. 入门级----测试的执行、环境的搭建、每日构建、测试记录和跟踪、回归测试、测试总结和报告...
  5. 【摘转留用】35前要考虑的
  6. Spark_Sql50题(DataFrame)
  7. 全局缓存管理工具-安装部署时提供小小的方便
  8. [BZOJ2049] [SDOI2008] 洞穴勘测
  9. Java Persistence with MyBatis 3(中国版)
  10. 课程作业----递归那些事
  11. (5)全局异常捕捉【从零开始学Spring Boot】
  12. Spring任务调度实战之Quartz Simple Trigger
  13. 《推荐系统实践》算法纯享(附代码链接)(一)—— 评价指标篇
  14. 熊猫直播破产背后:王思聪不肯再借钱,谋求卖身腾讯未果
  15. Ragel学习笔记(一)
  16. ArangoDB高级查询(一)
  17. 定时炸弹?揭露AmazonBasics电池背后的秘密
  18. 应聘PHP有面试题吗,php应聘面试题
  19. uboot命令之bootm详解
  20. C/C++新手学习项目(三) 魔兽世界之三:开战

热门文章

  1. QQ导出的txt聊天记录导入数据库方法
  2. [转]一淘网是如何实现系统架构的
  3. 京东商城禁止一淘网蜘蛛抓取内容
  4. excel函数交叉定位查找内容+根据内容查找行列号(反向查找)
  5. ue4渲染速度太慢_看虚幻引擎技术大神分享烧脑干货《克服VR眩晕之帧数:提升UE4内容实时渲染效率》...
  6. 用博客记录成长的历程
  7. 易语言禁止服务器,禁止指定程序联网易语言源码
  8. 解决异常:Premature end of chunk coded message body: closing chunk expected
  9. 将一个大写英文字母转换为小写输出 (12 分) - PTA
  10. SpringBoot Banner图标修改 + 文字生成器