CountDownLatch的使用

Posted hts-technology

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CountDownLatch的使用相关的知识,希望对你有一定的参考价值。

CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。类似join()的作用,join()也可以实现等待一些线程的完成,再执行后面线程。
CountDownLatch 例子:

package com.hts;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
    class Task1 implements Runnable{
        CountDownLatch countDownLatch;

        Task1(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            System.out.println("任务1执行了");
            countDownLatch.countDown();
        }
    }
    class Task2 implements Runnable{
        CountDownLatch countDownLatch;

        Task2(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            System.out.println("任务2执行了");
            countDownLatch.countDown();
        }
    }
    class Task3 implements Runnable{
        CountDownLatch countDownLatch;

        Task3(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            System.out.println("任务3执行了");
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        System.out.println("任务开始执行");
        executorService.submit(new CountDownLatchTest().new Task1(countDownLatch));
        executorService.submit(new CountDownLatchTest().new Task2(countDownLatch));
        executorService.submit(new CountDownLatchTest().new Task3(countDownLatch));  //位置①
        try {
            countDownLatch.await();
            System.out.println("三个任务执行完");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

执行结果:
技术分享图片

如果把位置①的那行代码注释掉,使得计数器CountDownLatch无法减到0,则会一直阻塞着,等待减到0.
结果如下:
技术分享图片





以上是关于CountDownLatch的使用的主要内容,如果未能解决你的问题,请参考以下文章

使用CountDownLatch模拟线程并发执行代码

CountDownLatch如何使用?

Java并发多线程编程——CountDownLatch

代码优化:CompletableFuture + countDownLatch + Vector

代码优化:CompletableFuture + countDownLatch + Vector

CountDownLatch 的使用