使用CompletableFuture踩的坑
坑才是重点,所以放在最前面阐述,希望能给大家解决问题提供一点帮助。
- 现象
通过CompletabltableFuture异步执行任务,并通过其whenComplete方法设置异步回调后,在回调方法中将值插入list或map中,结果发现获取不到回调方法中的值
public class CompletableFutureDemo02 {
/*
* 执行结果:data={}
* */
public static void main(String[] args) throws Exception {
Map<String, Integer> data = getData();
System.out.println("data=" + data);
}
/*
* 异步执行一系列耗时任务
* */
private static Map<String, Integer> getData() {
List<String> data = Arrays.asList("zhangsan", "lisi", "wangwu", "我是中国人");
Map<String, Integer> results = new HashMap<>();
List<CompletableFuture<Integer>> futures = new ArrayList<>();
data.forEach(name -> {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getLength(name));
// 设置回调
future.whenComplete((result, throwable) -> {
try {
// 回调方法执行逻辑消耗时间
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}