You need to enable JavaScript to run this app. 使用CompletableFuture实现并行循环时如何终止其他运行线程
优惠活动
大模型
产品
解决方案
定价
更多

使用CompletableFuture实现并行循环时如何终止其他运行线程

问题原因分析
  • 原有代码每次循环覆盖CompletableFuture引用,最终调用get()只能拿到最后一个提交任务的执行结果,无法捕获先触发停止条件的任务返回值
  • ExecutorService.shutdown()仅停止接收新任务,会等待所有已提交任务执行完成,不会中断正在运行的线程
  • shutdownNow()虽然会给线程发中断信号,但如果你的业务代码doTramLogicAndReturnAction没有响应中断、也没有检测停止标记的逻辑,线程依然会继续执行,不会停止
实现方案

我们可以用全局可见的停止标记 + 收集所有任务Future + 中断取消的组合方案实现需求,修改后的代码如下:

// 1、定义全局停止标记,AtomicBoolean保证多线程下的可见性和原子性
AtomicBoolean stopFlag = new AtomicBoolean(false);
ExecutorService pool = Executors.newFixedThreadPool(4);
// 2、收集所有提交的CompletableFuture,不要只保存最后一个
List<CompletableFuture<ResponseEntity<TramRealTimeResponse>>> futureList = new ArrayList<>();

for (TramRulesDTO rule : tramRulesResponse.getPayload()) {
    CompletableFuture<ResponseEntity<TramRealTimeResponse>> future = CompletableFuture.supplyAsync(() ->
    {
        // 执行业务前先判断是否已经触发停止,是则直接返回
        if (stopFlag.get()) {
            return null;
        }
        logger.info("thread " + Thread.currentThread().getName());

        TramRule tramRule = TramRuleFactory.getTramRule(rule.getRuleId());
        PartnerRuleDto partnerRuleDto = getPartnerRule(partnerRuleResponse.getPayload(), rule.getRuleId());

        if (Objects.nonNull(tramRule)) {
            try {
                // 如果doTramLogicAndReturnAction执行时间较长,可以在方法内部逻辑间隙也加入stopFlag的判断,及时终止执行
                tramRule.doTramLogicAndReturnAction(rule, partnerRuleDto,
                        paymentDetails, intermediaryDetails, partnerRulesConditions, tramRulesRequest);
            } catch (TramRealTimeException ex) {
                TramRealTimeResponse response = exceptionHandler.handleTramRealTimeException(ex, partnerRuleDto);
                if (response.getStatus().equals(200)) {
                    return null;
                } else {
                    // 触发停止逻辑
                    stopFlag.set(true);
                    // 中断所有正在运行的线程
                    pool.shutdownNow();
                    // 取消所有未完成的任务
                    futureList.forEach(f -> f.cancel(true));
                    return ResponseEntity.ok(response);
                }
            } catch (InterruptedException e) {
                // 响应shutdownNow()发来的中断信号,直接终止
                Thread.currentThread().interrupt();
                return null;
            }

        } else {
            return null;
        }
        return null;
    }, pool);
    futureList.add(future);
}

// 3、遍历所有Future获取第一个非空的返回结果,也就是触发停止的那个任务的返回值
ResponseEntity<TramRealTimeResponse> result = null;
for (CompletableFuture<ResponseEntity<TramRealTimeResponse>> future : futureList) {
    try {
        ResponseEntity<TramRealTimeResponse> res = future.get();
        if (res != null) {
            result = res;
            // 拿到结果后不需要再等其他任务
            break;
        }
    } catch (CancellationException | InterruptedException | ExecutionException e) {
        // 被取消的任务抛出异常直接忽略即可
    }
}
注意事项
  • 如果你的doTramLogicAndReturnAction方法执行耗时较长、内部有循环或者多步执行逻辑,可以在方法内部的执行间隙加入if(stopFlag.get() || Thread.currentThread().isInterrupted()) {return;}的判断,确保停止信号可以及时响应
  • 如果业务逻辑内部捕获了InterruptedException,不要直接吞掉,要记得重置中断标记Thread.currentThread().interrupt(),否则中断信号会失效

内容的提问来源于stack exchange,提问作者Truica Sorin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 17:18:03