CompletableFuture与CompletionStage
- CompletionStage是一个接口,定义了一系列对任务执行完成后的处理策略
- 接口大致分为三大类型
- 纯消费者模型, 对任务的执行结果进行消费
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor);
- 有返回值,对任务结果进行加工处理
public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
- 无返回值, 仅在任务完成之后,进行下一步动作
public CompletionStage<Void> thenRun(Runnable action);
CompletableFuture为CompletionStage的具体实现
- CompletableFuture的实例方式
CompletableFuture<String> future = CompletableFuture.completedFuture("ABC");
future.thenAccept(System.out:println);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
return "D";
});
future2.thenAccept(System.out:println);
CompletableFuture<String> future3 = CompletableFuture.runAsync(() -> doSomething1());
future3.thenRunAsync(() -> doSomething2()).thenRunAsync(() -> doSomething3());
CompletableFuture<Object> future4 = CompletableFuture.anyOf(future, future2);
future4.thenAccept(System.out:println);
CompletableFuture<Object> future5 = CompletableFuture.allOf(future, future2).join();
- 进阶用法
CompletableFuture.anyOf(CompletableFuture.supplyAsync(() -> 1), CompletableFuture.supplyAsync(() -> 2))
.thenCombineAsync(CompletableFuture.supplyAsync(() -> 3), (a, b) -> {
return (int) a + b;
}).thenApply(c -> c * 100)
.thenAccept(System.out::println);