并发编程辅助类CountDownLatch的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abcdad/article/details/81743471

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());
    }
}

猜你喜欢

转载自blog.csdn.net/abcdad/article/details/81743471