1. CompletableFuture
CompletableFuture 是JDK1.8版本新引入的类。主要作用就是进行任务的异步计算,通过函数式接口的方式帮助我们简化了异步计算的复杂性。
适用场景
当你的业务处理中需要对部分处理异步计算,且最终汇总计算结果时,CompletableFuture是你不二的选择。JDK1.5中也提供了Future接口,但是获取结果需要一直让CPU轮询,同时配合线程或者线程池的处理代码相对还是比较复杂的。
2. 创建异步任务
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)
- CompletableFuture 中提供了四个静态方法来创建任务任务,其中runAsync方法无返回值,supplyAsync有返回值。
- 方法中Executor参数用来指定执行异步任务的线程池,若不指定则默认使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。
3. 计算完成回调
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)
其中:
- whenComplete 是使用执行当前任务的线程(如main)去执行 whenComplete 中的任务。
- whenCompleteAsync 则是把后续的任务交给线程池,Executor 同样用来指定线程池。
回调方法非静态,需要配合上面 CompletableFuture 的对象进行调用。
示例:
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("1");
return "1";
});
future.whenCompleteAsync((r, tr) -> {
System.out.println("执行完成!");
});
}
如上代码是执行异步线程执行print(1)之后再异步执行print(执行完成),可以配合打印线程名称及sleep验证使用情况。
4. 串行化
当存在多个任务且相互依赖时,此时whenComplete回调无法满足需求了,CompletableFuture 提供了如下的方法
public CompletableFuture<Void> thenRun(Runnable var1)
public CompletableFuture<Void> thenAccept(Consumer<? super T> var1)
public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> var1)
- thenRun:单纯的等待上一个任务完成后执行,没有入参,也没有返回值
- thenAccept:等待上一个任务完成后的结果作为入参执行,没有返回值
- thenApply:等待上一个任务完成后的结果作为入参执行,有返回值
如上三个方法中都存在对应的Async方法,这里就不列出来了。
5. 组合处理
public static CompletableFuture<Void> allOf(CompletableFuture<?>... var0)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... var0)
- allOf 的含义是所有的 CompletableFuture 完成操作(如join)才可以做接下来的事情。
- anyOf 的含义是只要有任意一个 CompletableFuture 完成操作,就可以做接下来的事情。