MST

星途 面试题库

面试题:Java 中 CompletableFuture 多个任务 OR 组合关系 - 高级难度

现在有一组 CompletableFuture 任务列表,数量不定。要求实现一个方法,当这组任务中只要有一个成功完成,就返回这个成功任务的结果乘以 2,如果所有任务都失败,则返回 -1。请使用 Java 8 的 CompletableFuture 相关方法来实现这个功能,并考虑异常处理,写出完整的代码。
46.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

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

public class CompletableFutureExample {

    public static int handleCompletableFutures(List<CompletableFuture<Integer>> futures) {
        CompletableFuture<Integer> anyOfFuture = CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0]))
               .thenApply(future -> {
                    try {
                        return ((CompletableFuture<Integer>) future).get() * 2;
                    } catch (InterruptedException | ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                });

        CompletableFuture<Integer> resultFuture = anyOfFuture.exceptionally(ex -> -1);

        try {
            return resultFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            return -1;
        }
    }
}

你可以通过以下方式调用这个方法:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        futures.add(CompletableFuture.supplyAsync(() -> {
            // 模拟任务
            return 5;
        }));
        futures.add(CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("模拟异常");
        }));

        int result = CompletableFutureExample.handleCompletableFutures(futures);
        System.out.println("结果: " + result);
    }
}