线程池与CountDownLatch结合使用案例:
public List<Map<String, Object>> getHourlyAvgRainfall(List<String> hours, String addvcd) {
long systemStartTime = System.nanoTime();
List<Map<String, Object>> resultList = new CopyOnWriteArrayList<>();
int hourSize = hours.size();
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(hourSize);
final CountDownLatch latch = new CountDownLatch(hourSize);
for (int j = 0; j < hourSize; j++) {
String lastHour = hours.get(j);
executor.submit(() -> {
try {
Map<String, Object> map = new HashMap<>();
Map<String, Object> addvcdMap = new HashMap<>();
addvcdMap.put("lasthour", lastHour);
addvcdMap.put("addvcd", addvcd);
List<Map<String, Object>> hourlyAvgRainfall = stPptnRMapper.getHourlyAvgRainfall(addvcdMap);
long elapsedTimeMillis = (System.nanoTime() - systemStartTime) / 1000000;
logger.info(String.format("获取雨量站数据用时 %s 毫秒", elapsedTimeMillis));
List<Map<String, Object>> areaRainfallDistrict = getAreaRainfail_District(hourlyAvgRainfall);
logger.info(String.format("计算政区面雨量用时 %s 毫秒", (System.nanoTime() - systemStartTime) / 1000000));
map.put(lastHour, areaRainfallDistrict);
resultList.add(map);
latch.countDown();
} catch (Exception e) {
logger.error("Error processing hourly rainfall data", e);
}
});
}
// 等待所有任务完成
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for tasks to complete", e);
}
// 关闭线程池
executor.shutdown();
//时间排序
List<Map<String, Object>> collect = resultList.stream().sorted((e1, e2) -> RainCompare(e1, e2)).collect(Collectors.toList());
return collect;
}