项目场景:借助CountDownLatch解决并行执行相同任务后汇总问题
问题描述:
由于其他平台有限制,每次远程查询信息量只有20个,如果大于20个,那就需要进行多次查询汇总,这个时候借助线程池,并且使用CountDownLatch来控制请求达到什么样的条件之后才开始汇总数据。
业务执行内容:
public static Integer getNum() throws InterruptedException {
Thread.sleep(100);
return new Random().nextInt(1000);
}
单线程执行情况:
在主线程中,多次循环查询,当最后一次查询完毕之后再进行数据汇总
public static void test2() throws InterruptedException {
long startTime = System.currentTimeMillis();
List<Integer> lists = new ArrayList<>();
for (int i=0; i< 5; i++) {
lists.add(getNum());
}
for (int i =0; i<lists.size(); i++) {
System.out.println(lists.get(i));
}
System.out.println("耗时:"+ (System.currentTimeMillis()- startTime));
}
借助CountDownLatch和线程池:
public static void test1() throws Exception {
long startTime = System.currentTimeMillis();
ExecutorService executorService = Executors.newCachedThreadPool();
List<Integer> lists = new ArrayList<>();
final CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i =0; i< 5; i++) {
executorService.submit(()->{
try {
lists.add(getNum());
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
for (int i =0; i<lists.size(); i++) {
System.out.println(lists.get(i));
}
executorService.shutdown();
System.out.println("耗时:"+ (System.currentTimeMillis()- startTime));
}
# 时间对比: 线程池+CountDownLatch调用耗时:200 循环调用耗时:539