Java异步执行之CompletableFuture异步执行并获取结果使用
CompletableFuture介绍
CompletableFuture 是Java 8中引入的一个强大的异步编程工具,它实现了 Future 接口和 CompletionStage 接口。与传统的 Future 相比,CompletableFuture 提供了更多的控制能力,如手动完成、异常处理和多个Future的组合等。1.方法介绍
runAsync
创建没有返回值的异步任务
//默认线程池, 不一定会使用ForkJoinPool, 根据任务并行度来计算
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(ASYNC_POOL, supplier);
}
//可以自定以线程池
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
示例
public static <T,R> List<R> batchQuery(BatchQueryFunction<T,R> batchQueryFunction, List<T> t) throws Exception {
ThreadPoolUtils poolUtils = ThreadPoolUtils.get();//自定义线程池
AtomicReference<List<R>> listAtomicReference = new AtomicReference<>(Lists.newArrayList());//线程安全问题
CompletableFuture.allOf(t.stream().map(id -> CompletableFuture.runAsync(() -> {
R r = batchQueryFunction.accept(id);
List<R> jsonObjects = listAtomicReference.get();
jsonObjects.add(r);
listAtomicReference.set(jsonObjects);
},poolUtils).exceptionally(ex -> {//异常处理
log.error("Async operation failed",ex);
throw new RuntimeException(ex);
})).toArray(CompletableFuture[]::new)).join();// join阻塞获取所有结果
log.info("list size: {}", listAtomicReference.get().size());
shutdownThreadPool(poolUtils);//关闭线程池
return listAtomicReference.get();
}
supplyAsync
supplyAsync是创建带有返回值的异步任务, 也是有两个方法
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(ASYNC_POOL, supplier);
}
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
示例
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
return 1;
}catch(InterruptedException e) {
e.printStackTrace();
}
return 0;
});
Integer i = integerCompletableFuture.get();
System.out.println("i = " + i);
}
2.异步回调
处理计算结果thenApply ,要回调的结果
CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "等一会!");
CompletableFuture<String> future = completableFuture
.thenApply(s -> s + "等到你了");
System.out.println("future = " + future.get()); //future = 等一会!等到你了
不要回调的结果使用thenAccept
CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "等一会!");
CompletableFuture<Void> future1 = completableFuture
.thenAccept(s1-> System.out.println("future1 = " + s1));
future1.get();
}

浙公网安备 33010602011771号