学习多线程之CountDownLatch使用

「这是我参与2022首次更文挑战的第26天,活动详情查看:2022首次更文挑战

写在前面

我们今天来学习多线程中的另一个工具类CountDownLatch,名叫同步计数器。

和昨天的文章中的Semaphore信号量工具一样,都是实现多线程中锁的工具类。

那下面我们就来看一下这个工具类到底如何使用吧。

学习多线程之CountDownLatch使用

CountDownLatch,同步计数器,功能和他的名称一样,就是用来计数的,但是这个数字是递减的数字,在线程操作时,这个数字只有递减到0时,才能使得指定的线程开始运行。

我们还是来看一下这个工具类是如何使用的吧,从如下代码中看看:

public static void main(String[] args) throws InterruptedException {
    CountDownLatch countDownLatch = new CountDownLatch(4);
    Thread thread0 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread0运行ing"+System.currentTimeMillis());
            countDownLatch.countDown();
        }
    });
    Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread1运行ing"+System.currentTimeMillis());
            countDownLatch.countDown();
        }
    });
    Thread thread2 = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread2运行ing"+System.currentTimeMillis());
            countDownLatch.countDown();
        }
    });
    Thread thread3 = new Thread(new Runnable() {
        @SneakyThrows
        @Override
        public void run() {
            System.out.println("thread3运行ing"+System.currentTimeMillis());
            Thread.sleep(3000);
            countDownLatch.countDown();
        }
    });
    thread0.start();
    thread1.start();
    thread2.start();
    thread3.start();
    countDownLatch.await();
    System.out.println("主线程开始执行"+System.currentTimeMillis());
}
复制代码

我们试着运行这个代码示例,可以得到一个结果,如下:

thread0运行ing1645867471594

thread2运行ing1645867471595

thread1运行ing1645867471596

thread3运行ing1645867471596

主线程开始执行1645867474606

从代码中,我们首先声明了一个CountDownLatch对象,并且将其填充了4个位,代表这个对象可以被递减四次。

接着,通过四个线程同时执行,前三个线程没有任何的区别,只是打印出当前时间和将CountDownLatch对象进行递减。

但是我们将第四个线程睡眠三秒钟;然后在主线程中执行了await方法,通过这个方法,可以让主线程等待CountDownLatch对象递减到0才可以开始运行。

通过这个结果,我们也获得到了想要的结果,主线程等待了三秒钟后,才正常运行起来。

这就是CountDownLatch工具类的使用方法了。

猜你喜欢

转载自juejin.im/post/7068951199260606501