//每次查多少条
int limit = 200;
//查询数据总条数
long count = baseMapper.getRelayDetailCount(powerDetailDto.getCustomerCategory());
//线程计数器
CountDownLatch latch = new CountDownLatch(10);
//手动创建多线程
ThreadPoolExecutor executorService = new ThreadPoolExecutor(8, 15, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(20),
new ThreadPoolExecutor.CallerRunsPolicy());
//遍历
for (int i = 0; i < (int) count / limit + 1; i++) {
final int currentIndex = i;
executorService.submit(() -> {
long startIdx = currentIndex * limit;
long endIdx = (currentIndex + 1) * limit;
if (endIdx > count) {
endIdx = count;
}
//查询数据
List<MeterDetailVo> relayDetail = baseMapper.getRelayDetail(powerDetailDto.getCustomerCategory(), startIdx, endIdx);
latch.countDown(); // 通知完成
});
}
try {
// 等待所有任务完成
latch.await();
// 没有异常发生,开始关闭线程池
executorService.shutdown();
// 等待线程池关闭完成,或者达到超时时间
if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
// 如果超时,强制关闭线程池
executorService.shutdownNow();
}
} catch (InterruptedException e) {
// 发生中断异常,重新设置中断状态
Thread.currentThread().interrupt();
// 尝试关闭线程池
executorService.shutdownNow();
}