CompletableFuture实现了Future和CompletionStage两个接口,CompletionStage可以看做是一个异步任务执行过程的抽象。我们可以基于CompletableFuture方便的创建任务和链式处理多个任务。下面我们通过实例来介绍它的用法。
1.异步无返回
CompletableFuture<Void> futureAsync = CompletableFuture.runAsync(() -> {
System.out.println("业务代码");
});
2.异步有返回
CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {
//业务代码
return T;
});
3.引入线程池
ExecutorService exector = Executors.newFixedThreadPool(10);
CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {
// 业务代码
return T;
}, executor);
4.阻塞拿结果
CompletableFuture.get()
5.异步拿结果
CompletableFuture<T> future = CompletableFuture.supplyAsync(() -> {
// 业务代码
return T;
});
future.whenComplete((result, exception) -> {
if (null == exception) {
//正常结果
} else{
//有异常
}
});
6.异常与结果分开处理,可单独处理结果或异常
CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("error");
}).exceptionally(ex -> {
//异常信息处理
return ex.getMessage();
}).thenAccept(result -> {
//结果处理
});
7.子线程之间需依赖结果传递
CompletableFuture.supplyAsync(() -> {
return "result1";
}).thenApply(previousResult -> {
return previousResult + " result2";
}).thenApply(previousResult -> {
return previousResult + " result3";
}).thenAccept(previousResult -> {
System.out.println(previousResult);
});
控制台打印如下:
result1 result2 result3
8.嵌套调用
CompletableFuture<CompletableFuture<T>> res = method1().thenApply(result1 -> {
return method2(result1);
});
9.组合调用
CompletableFuture<T> res = method1().thenCompose(result1 -> {
return method2(result1);
});
10.多线程并行处理
10.1收集子线程
List<CompletableFuture> cfList = new ArrayList<CompletableFuture>();
for (int i = 0; i < 业务集合; i++) {
CompletableFuture<T> cf = CompletableFuture.supplyAsync(() -> {
return customMethod();
}, executor);
cfList.add(cf);
}
10.2 统一控制所有子线程
CompletableFuture<Void> allFutures =
CompletableFuture
.allOf(cfList.toArray(new CompletableFuture[cfList.size()]));
10.3 阻塞所有子线程
allFutures .get()
10.4异步获取所有子线程结果
CompletableFuture<List<T>> allChildCfResultList= allFutures.thenApply(v -> {
return cfList.stream().map(cf-> cf.join())
.collect(Collectors.toList());
});
10.5 任意子线程结束即返回结果
CompletableFuture<T> anyOfFutures = CompletableFuture.anyOf(cf1, cf2, cf3);