面试题答案
一键面试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);
}
}