并发编程辅助类CountDownLatch的用法

CountDownLatch类位于java.util.concurrent包下,利用它可以实现计时功能。比如有10个任务,需要统计执行完成10个任务一共花了多长时间,此时就可以利用CountDownLatch来实现这种功能了。

package com.test.concurrent;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.commons.lang3.time.FastDateFormat;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@FixMethodOrder(MethodSorters.JVM)
public class TestCountDownLatch {

    private static final FastDateFormat fdf = FastDateFormat.getInstance("yyy-MM-dd HH:mm:ss");

    private ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5,
            new BasicThreadFactory.Builder().namingPattern("test-schedule-pool-%d").daemon(true).build());

    @Test
    public void testCountDownLatch() throws Exception {
        Date startDate = new Date();

        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            String seconds = String.valueOf(i);
            executorService.submit(() -> {
                try {
                    TimeUnit.SECONDS.sleep(Integer.valueOf(seconds));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("线程[{}]正在休眠[{}s]", Thread.currentThread().getName(), seconds);
                /**将count值减1*/
                countDownLatch.countDown();
            });
        }
        /**调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行*/
        countDownLatch.await();

        Date endDate = new Date();
        log.info("开始时间[{}],结束时间[{}],耗时[{}ms]", fdf.format(startDate), fdf.format(endDate), endDate.getTime() - startDate.getTime());
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值