【Java】并发处理示例

导入包

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

单个手动获取

List<Dictionary> dictionaryList;
List<CatalogAggregationVo> aggregationVoList;
ExecutorService executorService = Executors.newFixedThreadPool(2);
try {
    CompletableFuture<List<Dictionary>> dictionaryListFuture = CompletableFuture.supplyAsync(() -> adminFeign.getDictionaryByIndexId("column_type").getData(), executorService);
    CompletableFuture<List<CatalogAggregationVo>> aggregationVoListFuture = CompletableFuture.supplyAsync(() -> catalogAggregationService.getCatalogAggregationBySiteId2(siteId), executorService);
    // 等待所有任务完成
    CompletableFuture<Void> allFutures = CompletableFuture.allOf(dictionaryListFuture, aggregationVoListFuture);
    // 设置等待时间
    allFutures.get(10, TimeUnit.MINUTES);
    dictionaryList = dictionaryListFuture.get();
    aggregationVoList = aggregationVoListFuture.get();
} catch (Exception e) {
    dictionaryList = new ArrayList<>();
    aggregationVoList = new ArrayList<>();
} finally {
    executorService.shutdown();
}

循环获取

List<StationGroup> siteList = stationGroupService.getAllStationGroup();
if (CollectionUtil.isEmpty(siteList)) {
    return null;
}
// 线程池
ExecutorService executor = Executors.newFixedThreadPool(Math.min(siteList.size(), 10));
List<Map<String, Long>> countList = new ArrayList<>();
try {
    // 并行查询每个站点的知识库件数
    List<CompletableFuture<Map<String, Long>>> futures = siteList.stream()
            .map(site -> CompletableFuture.supplyAsync(() -> this.countLibraryBySiteAndTime(site.getId(), startTime, endTime), executor))
            .collect(Collectors.toList());
    // 等待所有任务完成,设置超时时间60秒
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(10, TimeUnit.MINUTES);
    // 收集结果
    for (CompletableFuture<Map<String, Long>> future : futures) {
        countList.add(future.get());
    }
} catch (Exception e) {
    log.error("并行统计知识库件数异常", e);
} finally {
    executor.shutdown();
}

 

posted @ 2026-06-25 14:20  谷粒-笔记  阅读(8)  评论(0)    收藏  举报