当多个线程企图调用同一个CompletableFuture的complete、cancel方法时,只有一个会成功
使用默认的线程池执行异步任务,如果没有显式指定线程个数,默认线程个数等于当前机器上可用的CPU个数
1.无返回值的方法
public static Void hasNoReturn() throws ExecutionException, InterruptedException {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> doAnything();
return future.get();
}
输出 null
runAsync() 方法没有返回值 因此使用 future.get() 永远返回null
2.有返回值的方法
public static String hasReturn() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "1");
return future.get();
}
输出 1
supplyAsync() 方法有返回值 可通过计算得到返回结果
3.使用一个异步任务的结果作为另一个异步任务的参数
1.无返回值
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "1");
CompletableFuture<Void> future2 =future.thenRun(() -> System.out.println("ok"));
thenRun() 方法
2.无返回值但可以拿到上个任务的结果
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "1");
CompletableFuture<Void> future2 =future.thenAccept(s -> s = s+"2");
thenAccept() 方法
3.有返回值
public static String hasReturn() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "1");
CompletableFuture<String> future2 =future.thenApply(s -> {
s = s + "2";
return s;
});
return future2.get();
}
输出为 12 参数中的 s 为future任务执行完毕的结果
future2的结果是基于future的结果得到的,
如果执行get()方法时future/future2没有计算完成, 则会阻塞
4.强制设置结果
public static String hasReturn() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "1");
future.complete("2");
return future.get();
}
输出 2
5.多个CompletableFuture组合运算
1. 当一个CompletableFuture执行完执行另一个CompletableFuture
public static CompletableFuture<String> doSomething1(String id) {
return CompletableFuture.supplyAsync(() -> id);
}
public static CompletableFuture<String> doSomething2(String id) {
return CompletableFuture.supplyAsync(() -> id + "1");
}
public static String getResult() throws ExecutionException, InterruptedException {
CompletableFuture<String> result = doSomething1("123").thenCompose(Feature::doSomething2);
return result.get();
}
执行完doSomething1后执行doSomething2 结果为1231
2. 实现两个并发的CompletableFuture完成后,将结果作为参数计算
public static String getResult() throws ExecutionException, InterruptedException {
CompletableFuture<String> result = doSomething1("123").thenCombine(doSomething2("456"),
(one, two) -> one + two);
return result.get();
输出 1234561
6.Stream流与异步结合
public static List<String> getResult() {
List<CompletableFuture<String>> completableFutures;
List<String> list = Arrays.asList("li", "lin");
--循环传入参数--
completableFutures = list.stream().map(Feature::doSomething2).collect(Collectors.toList());
--获取每个异步任务的结果并存放于列表中
return completableFutures.stream().map(CompletableFuture::join).collect(Collectors.toList());
}
输出为 [li1, lin1]
CompletableFuture 基础用法介绍完毕
摘自 <<Java异步编程实战>>