面试题答案
一键面试- 确保
thenRun
方法中的任务在特定线程池中执行:CompletableFuture
的thenRun
方法可以通过调用thenRunAsync
方法并传入自定义的Executor
来实现在特定线程池中执行任务。Executor
可以是Executors
工具类创建的线程池,也可以是自定义的线程池。
- 前序异步任务抛出异常时
thenRun
方法中的任务执行情况:- 如果前序异步任务抛出异常,
thenRun
方法中的任务不会执行。
- 如果前序异步任务抛出异常,
- 处理异常并确保有补救措施:
- 可以使用
exceptionally
方法来捕获前序任务的异常,并在捕获到异常时执行补救措施。 以下是代码示例:
- 可以使用
import java.util.concurrent.*;
public class CompletableFutureExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletableFuture.supplyAsync(() -> {
// 模拟一个可能抛出异常的异步任务
if (Math.random() > 0.5) {
throw new RuntimeException("任务执行出错");
}
return "任务正常完成";
})
.thenRunAsync(() -> System.out.println("这是thenRunAsync中的任务,在特定线程池中执行"), executor)
.exceptionally(ex -> {
System.out.println("捕获到异常: " + ex.getMessage());
// 执行补救措施
return "补救措施执行结果";
})
.thenAccept(System.out::println);
executor.shutdown();
}
}
解释:
supplyAsync
方法开始一个异步任务。thenRunAsync
方法传入自定义的Executor
(这里是executor
线程池),确保其中的任务在特定线程池中执行。exceptionally
方法捕获前序任务的异常,并执行补救措施,返回补救措施的结果。thenAccept
方法接收最终结果(正常结果或补救措施的结果)并打印。最后关闭线程池。