【Java】CompleteableFuture注意事项

 // CompleteableFuture的任务队列
 List<CompletableFuture<Void>> executionFutureList;
 // 记录开始时间
 LocalDateTime now = LocalDateTime.now();
 for (String str : strList) {
    // 初始化任务队列
    executionFutureList = new ArrayList<>();
    // 业务逻辑, 使用自定义线程池执行而非底层默认JVM ForkJoinPool线程池
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> businessLogic(), completeableFutureExecutor);
    // 任务队列添加任务
    executionFutureList.add(future);
}
// 任务队列阻塞等待所有任务完成
CompletableFuture.allOf(executionFutureList.toArray(new CompletableFuture[0]))
    .thenRun(() -> log.info("业务逻辑已完成,开始时间{}, 结束时间{}", now, LocalDateTime.now()))
    .join();

以上代码问题就出在

// 初始化任务队列
executionFutureList = new ArrayList<>();

这样初始化会导致阻塞 allOf()+join() 并不会等待所有任务都完成

应该将初始化任务队列放到for循环外部

// CompleteableFuture的任务队列
 List<CompletableFuture<Void>> executionFutureList = new ArrayList<>();
 // 记录开始时间
 LocalDateTime now = LocalDateTime.now();
 for (String str : strList) {
    // 业务逻辑, 使用自定义线程池执行而非底层默认JVM ForkJoinPool线程池
    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> businessLogic(), completeableFutureExecutor);
    // 任务队列添加任务
    executionFutureList.add(future);
}
// 任务队列阻塞等待所有任务完成
CompletableFuture.allOf(executionFutureList.toArray(new CompletableFuture[0]))
    .thenRun(() -> log.info("业务逻辑已完成,开始时间{}, 结束时间{}", now, LocalDateTime.now()))
    .join();

 

posted @ 2025-04-16 09:38  onejay  阅读(29)  评论(0)    收藏  举报