一、CompletableFuture 概述
-
CompletableFuture 在 Java 里面被用于异步编程,异步通常意味着非阻塞,可以使得任务单独运行在与主线程分离的其他线程中,并且通过回调可以在主线程中得到异步任务的执行状态,是否完成,和是否异常等信息
-
CompletableFuture 实现了 Future, CompletionStage 接口,实现了 Future 接口就可以兼容现在有线程池框架,而 CompletionStage 接口是异步编程的接口抽象,里面定义多种异步方法,通过这两者集合,从而打造出了强大的 CompletableFuture 类
二、CompletableFuture 使用
1、无返回值的异步任务
(1)相关方法
- runAsync 方法:异步调用没有返回值
public static CompletableFuture<Void> runAsync(Runnable runnable) {return asyncRunStage(asyncPool, runnable);
}
- get 方法:阻塞直到任务结束后获取返回值
public T get() throws InterruptedException, ExecutionException {Object r;return reportGet((r = result) == null ? waitingGet(true) : r);
}
(2)具体实现
CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {System.out.println(Thread.currentThread().getName() + " 1");
});
completableFuture1.get();
- 结果
ForkJoinPool.commonPool-worker-9 1
2、有返回值的异步任务
(1)相关方法
- supplyAsync 方法:异步调用有返回值
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {return asyncSupplyStage(asyncPool, supplier);
}
- get 方法:阻塞直到任务结束后获取返回值
public T get() throws InterruptedException, ExecutionException {Object r;return reportGet((r = result) == null ? waitingGet(true) : r);
}
- whenComplete 方法:异步调用完成后进行执行相关操作
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) {return uniWhenCompleteStage(null, action);
}
(2)具体使用
CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " 2");return 1024;
});
completableFuture2.whenComplete((t, u) -> {// 参数 t 为返回值System.out.println(t);// 参数 u 为异常System.out.println(u);
});
- 结果
ForkJoinPool.commonPool-worker-9 2
1024
null
