面试题答案
一键面试import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
// 模拟A任务
if (Math.random() < 0.5) {
throw new RuntimeException("A任务执行出错");
}
return "A任务返回的字符串";
})
.thenApplyAsync(str -> {
// 模拟B任务,使用A任务返回的字符串
if (Math.random() < 0.5) {
throw new RuntimeException("B任务执行出错");
}
return str.length();
})
.thenApplyAsync(num -> {
// 模拟C任务,使用B任务返回的整数
if (Math.random() < 0.5) {
throw new RuntimeException("C任务执行出错");
}
return num * 2;
})
.exceptionally(ex -> {
// 捕获并处理异常
System.out.println("捕获到异常: " + ex.getMessage());
return -1;
})
.thenAccept(System.out::println);
// 防止主线程退出
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
上述代码通过CompletableFuture
实现了三个异步任务的顺序执行,并且在每个任务执行出错时能够捕获异常并进行处理。具体解释如下:
supplyAsync
方法创建并异步执行A任务,它返回一个CompletableFuture<String>
。thenApplyAsync
方法接收A任务的结果,并将其作为参数传递给B任务,B任务返回一个CompletableFuture<Integer>
。- 再次使用
thenApplyAsync
方法,接收B任务的结果,并将其作为参数传递给C任务,C任务返回一个CompletableFuture<Integer>
。 exceptionally
方法用于捕获前面任务中抛出的异常,并进行处理,返回一个默认值。thenAccept
方法用于消费C任务最终的结果或exceptionally
处理后的结果,并打印输出。- 最后通过
Thread.sleep
防止主线程退出,确保异步任务有足够时间执行。