CountDownLatch的应用与原理

一、什么是CountDownLatch

CountDownLatch是具有synchronized机制的一个工具,目的是让一个或者多个线程等待,直到其他线程的一系列操作完成。

CountDownLatch初始化的时候,需要提供一个整形数字,数字代表着线程需要调用countDown()方法的次数,当计数为0时,线程才会继续执行await()方法后的其他内容。CountDownLatch(int count);

二、CountDownLatch对象中的方法

  1. CountDownLatch(int count):count为计数器的初始值(一般需要多少个线程执行,count就设为几)。
  2. countDown(): 每调用一次计数器值-1,直到count被减为0,代表所有线程全部执行完毕。
  3. getCount():获取当前计数器的值。
  4. await(): 等待计数器变为0,即等待所有异步线程执行完毕。
  5. boolean await(long timeout, TimeUnit unit): 此方法与await()区别:

①此方法至多会等待指定的时间,超时后会自动唤醒,若 timeout 小于等于零,则不会等待
②boolean 类型返回值:若计数器变为零了,则返回 true;若指定的等待时间过去了,则返回 false

三、CountDownLatch使用

首先我们先使用join阻塞等待线程完成

首先建立3个线程。

public class Worker1 implements Runnable {
    @Override
    public void run() {
        System.out.println("-线程1启动");
        try {
            Thread.sleep(13_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程1完成--我休眠13秒\r\n");
    }
}

public class Worker2 implements Runnable {
    @Override
    public void run() {
        System.out.println("-线程2启动");
        try {
            Thread.sleep(3_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程2完成--我休眠3秒\r\n");
    }
}

public class Worker3 implements Runnable {
    @Override
    public void run() {
        System.out.println("-线程3启动");
        try {
            Thread.sleep(3_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        try {
            Thread.sleep(3_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程3完成--我休眠6秒\r\n");
        System.out.println();
    }
}


public class Main {
    public static void main(String[] args) throws InterruptedException {
        Worker1 worker1 = new Worker1();
        Worker2 worker2 = new Worker2();
        Worker3 worker3 = new Worker3();

        Thread thread1 = new Thread(worker1,"线程1");
        Thread thread2 = new Thread(worker2,"线程2");
        Thread thread3 = new Thread(worker3,"线程3");

        thread1.start();
        thread2.start();
        thread3.start();

        thread1.join();
        thread2.join();
        thread3.join();
        System.out.println("主线程结束....");

    }
}

 结果如下所示:

可以看出三个线程是并行执行的。启动顺序,并不和执行完毕的顺序一致,但可以明确的是,主线程为一直阻塞,直到三个线程执行完毕。

使用CountDownLatch模拟并发

    CountDownLatch countDownLatch = new CountDownLatch(1);
    for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                    try {
                            //所有请求都阻塞在这,等待
                            countDownLatch.await();
                            // 调用测试接口
                            System.out.println(Thread.currentThread().getName() + "开始执行……");
                    } catch (InterruptedException e) {
                            e.printStackTrace();
                    }
            }).start();
    }
    // 让请求都准备好
    Thread.sleep(2000);
    // 让所有请求统一请求
    countDownLatch.countDown();

单个线程等待:多个线程(任务)完成后,进行汇总合并 

        int count = 3;
        CountDownLatch countDownLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            final int index = i;
            new Thread(() -> {
                    try {
                            Thread.sleep(1000 + ThreadLocalRandom.current().nextInt(1000));
                            System.out.println("finish" + index + Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                            e.printStackTrace();
                    }finally{
                            countDownLatch.countDown();
                    }
            }).start();
        }
        countDownLatch.await();// 主线程在阻塞,当计数器==0,就唤醒主线程往下执行。
        System.out.println("主线程:在所有任务运行完成后,进行结果汇总");

 我们可以看到如下结果是主线程一直阻塞一直等待计数器==0才唤醒主线程继续执行的。

 

四、CountDownLatch原理

CountDownLatch是通过AQSstate字段来实现的一个计数器,计数器的初始值(state的值)为new CountDownLatch设置的数量,每次调用countDown的时候,state的值会进行减1,最后某个线程将state值减为0时,会把调用了await()进行阻塞等待的线程进行唤醒。CountDownLatch重写了tryReleaseShared这个方法,只有当state这个字段被设置为0时,也就是tryReleaseShared返回true的情况就会执行doReleaseShared方法,把调用了await的线程进行唤醒。

  public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
 protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

用草书谱写兰亭序

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值