MST
星途 面试题库

面试题:Java中CompletableFuture异步任务执行结果如何存储到List中

在Java中,给定多个CompletableFuture异步任务,如何将它们的执行结果存储到一个List集合中,并确保所有任务完成后才进行操作,请写出核心代码片段。
21.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 定义多个CompletableFuture任务
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 1);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 2);
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> 3);

        // 将所有CompletableFuture任务放入一个List
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        futures.add(future1);
        futures.add(future2);
        futures.add(future3);

        // 使用CompletableFuture.allOf等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));

        // 获取所有任务的结果并放入一个List
        List<Integer> results = new ArrayList<>();
        allFutures.thenRun(() -> {
            futures.forEach(future -> {
                try {
                    results.add(future.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            });
        }).get();

        System.out.println(results);
    }
}