CompletableFuture 异步编程
Java8 新增一个类 CompletableFuture
,用来支持流式异步编程。
创建任务
CompletableFuture
提供一下API用来执行异步任务。
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);
static CompletableFuture<Void> runAsync(Supplier<U> supplier);
static CompletableFuture<Void> runAsync(Supplier<U> supplier, Executor executor);
这些API都是用来创建任务,并且异步计算任务。supplyAsync
方法是有返回值的。例如:
CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture<Void> futureB = CompletableFuture.supplyAsync(() -> "hello");
thenAccept()
CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action);
CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor);
表示当前这个阶段计算正常完成(没有异常发送),计算完成后的结果会作为 thenAcceptAsync
方法的入参,然后执行 action
。如果当前阶段计算发送异常,thenAcceptAsync
方法不会被执行。
// 打印 hello
CompletableFuture.supplyAsync(() -> "hello")
.thenAcceptAsync(result -> System.out.println(result));
// 不会打印. 因为不会执行thenAcceptAsync
CompletableFuture.supplyAsync(() -> {
throw new NullPointerException();
})
.thenAcceptAsync(rs -> System.out.println("1234"));
thenApply()
<U> CompletableFuture<U> thenApply(Function<?