上一节我们主要讲解了如何创建一个异步任务及入门示例。详情点击CompletableFuture系列-简单方法&入门示例01
CompletableFuture实现了两个接口:
1、Future
解决异步操作什么时候结束,如方法get()、isDone()
2、CompletionStage
解决异步操作的结果如何获取。在1.8版本中CompletionStage有40个方法。
我们都知道任务执行是有时序关系的。
- 串行:前一个任务执行完才能执行后一个任务。
- 并行:多个任务可以并行执行。
- 汇聚:将多个任务的执行结果聚合。
汇聚又可以分为:
1)AND聚合:所有依赖的任务全部执行完才能进行下一步。
2)OR聚合:依赖的任务只要有一个完成就可以进行下一步。
CompletionStage接口可以清晰的描述这种时序关系。
这一节我们就来讲述一下串行执行。
1、描述串行关系
thenApply、thenAccept、thenRun、thenCompose
public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn);
public <U> CompletionStage<U> thenApplyAsync(Function<? super T,? extends U> fn,Executor executor);
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 CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);
public <U> CompletionStage<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletionStage<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn);
public <U> CompletionStage<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn,Executor executor);
1)系列方法介绍
①*thenApply
系列和thenCompose
系列*:接受的是Function类型的参数R apply(T t);
,有返回值,有入参。不同的是,thenCompose
的方法会创建出一个子流程,最终结果的thenApply系列是相同的。
②*thenAccept
系列*:接受的是Consumer类型的参数void accept(T t);
,无返回值,有入参。
🌂*thenRun
系列*:接受的是Runnable类型的参数void run();
,无返回值,无入参。
2)Async:指的是异步执行fn、comsumer、action
3) executor:在指定线程池执行;否则使用默认的ForkJoinPool线程池,这个线程池默认创建的线程数是CPU的核数,也可以通过JVM option:-Djava.util.concurrent.ForkJoinPool.common.parallelism
来设置ForkJoinPool的线程数。
以常用的thenApply
举例,接受的是Function类型的参数。
2、代码示例:
import java.util.concurrent.CompletableFuture;
public class CompletableFutureDemo {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<User> apply = CompletableFuture.supplyAsync( //1、创建异步任务
() -> requstId()) //2、获取请求id
.thenApply(id -> getUserById(id)); //3、根据请求id获取用户信息
System.out.println(apply.join().toString());
}
public static int requstId() {
return 1;
}
public static User getUserById(int id) {
User user = new User(1, "Lindsay98");
if (id == user.getId()) {
return user;
} else {
return null;
}
}
}
其中第2、3步是串行执行,第3步依赖第2步的执行结果。
- 下一节:请期待异步任务并行执行