跳至主要內容

CountDownLatch

chanchaw大约 2 分钟java

概述

通过 CountDownLatch 等待多线程任务执行完毕后继续下面的业务逻辑,将多线程归纳为顺序执行

代码

// 测试多线程协同工作
public void testCountDownLatch() throws InterruptedException {
    int len = 5;// 线程数量,也是循环的数量
    List<Long> randomList = getRandomListLong(len,1000);// 小于1的浮点数*1000后得到适用于毫秒的Long类型的数字
    Long total = 0L;
    CountDownLatch latch = new CountDownLatch(randomList.size());
    Date startTime = new Date();
    System.out.println("开始循环时间:" + DateUtil.getFormatDate(startTime,"yyyy-MM-dd HH:mm:ss.SSS"));
    for (int i = 0; i < len; i++) {
        Long aLong = randomList.get(i);
        total += aLong;// 统计累计休眠时间
        System.out.println("第" + i + "次循环休眠毫秒数:" + aLong);
        taskExecutor.execute(() -> {
            try {
                Thread.sleep(aLong);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                latch.countDown();
            }
        });
    }
    System.out.println("循环结束时间:" + DateUtil.getFormatDate(new Date(),"yyyy-MM-dd HH:mm:ss.SSS"));
    latch.await();
    Date endTime = new Date();
    System.out.println("latch.await()结束时间:" + DateUtil.getFormatDate(endTime,"yyyy-MM-dd HH:mm:ss.SSS"));
    long duration = endTime.getTime() - startTime.getTime();
    System.out.println("多线程任务执行耗时:" + duration);
    System.out.println("所有线程累计休眠毫秒数:" + total);
}

/**
 * 返回指定数量的随机数
 * @param len 集合中元素的个数
 * @return 小于1的浮点数构成的集合
 */
public List<Double> getRandomList(int len){
    if(len == 0) len = 3;
    List<Double> seconds = new ArrayList<>();
    double random = 0;
    for (int i = 0; i < len; i++) {
        random = Math.random();
        seconds.add(random);
    }
    return seconds;
}

public List<Long> getRandomListLong(int len,int ratio){
    if(len == 0) len = 3;
    if(ratio == 0) ratio = 1000;
    List<Long> seconds = new ArrayList<>();
    double random = 0;
    for (int i = 0; i < len; i++) {
        random = Math.random();
        random = random * 1000;
        seconds.add((long) random);
    }
    return seconds;
}

/* 测试结果:
开始循环时间:2024-03-11 13:50:01.998
第0次循环休眠毫秒数:201
第1次循环休眠毫秒数:14
第2次循环休眠毫秒数:982
第3次循环休眠毫秒数:7
第4次循环休眠毫秒数:291
循环结束时间:2024-03-11 13:50:02.009
latch.await()结束时间:2024-03-11 13:50:03.019
多线程任务执行耗时:1021
所有线程累计休眠毫秒数:1495
*/