实现思路
- 使用
CompletableFuture.allOf
方法并行执行所有任务。
- 为每个
CompletableFuture
任务添加exceptionally
回调,在任务抛出异常时捕获并记录异常信息。
- 通过
join
方法等待所有任务完成,由于exceptionally
已经处理了异常,join
不会抛出异常中断程序。
核心代码片段
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
public class CompletableFutureExample {
private static final Logger logger = Logger.getLogger(CompletableFutureExample.class.getName());
public static void main(String[] args) {
CompletableFuture<Void> future1 = CompletableFuture.supplyAsync(() -> {
if (Math.random() < 0.5) {
throw new RuntimeException("Task 1 failed");
}
return "Task 1 completed";
}).exceptionally(ex -> {
logger.severe("Exception in Task 1: " + ex.getMessage());
return null;
});
CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(() -> {
if (Math.random() < 0.5) {
throw new RuntimeException("Task 2 failed");
}
return "Task 2 completed";
}).exceptionally(ex -> {
logger.severe("Exception in Task 2: " + ex.getMessage());
return null;
});
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
try {
allFutures.join();
logger.info("All tasks completed or exceptions handled.");
} catch (Exception e) {
// This block won't be reached as exceptions are handled in exceptionally
}
}
}