JUC--CountDownLatch简介和使用

1 概述

在我们的项目开发当中,我们通常会遇到这样的问题,一个线程的执行要等到其余几个线程执行完成才能开始,这种情况我们怎么办呢?这里就可以使用到我们JUC下面的并发工具类CountDownLatch。

2 示例


import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
/**
 * @Author:LIUTAO
 * @Description:
 * @Date:Created in 8:14 2018/5/6
 * @Modified By:
 */
public class CountDownLatchDemo {
 
    static final CountDownLatch countDownLatch = new CountDownLatch(5);
    public static CountDownLatchRunnable countDownLatchDemo = new CountDownLatchRunnable();
 
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(countDownLatchDemo);
        }
        countDownLatch.await();
 
        System.out.println("All threads have been executed completely");
        executorService.shutdown();
    }
 
    public static class CountDownLatchRunnable implements Runnable {
        public void run() {
            //simulate the task of checking
            try {
                Thread.sleep(new Random().nextInt(10) * 1000);
                System.out.println(Thread.currentThread().getId() + "check complete");
                countDownLatch.countDown();
                System.out.println("state:"+countDownLatch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

程序输出结果如下:

12check complete
state:4
14check complete
state:3
16check complete
state:2
15check complete
state:1
13check complete
state:0
All threads have been executed completely

通过上面的列子我们可以看见countDown()一次,state就变小一次,直到变为0的时候主线程就开始执行。

上面就是对CountDownLatch使用的简单介绍,下一篇文章,我们会对CountDownLatch的源码进行分析。

    原文作者:JUC
    原文地址: https://blog.csdn.net/ONROAD0612/article/details/82108187
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞