线程并发控制:CountDownLatch闭锁

一、闭锁的作用

Latch中文含义有门闩之意,闭锁的作用相当于一扇门:CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,然后在CountDownLatch上等待的线程就可以恢复执行任务。

二、闭锁的使用场景

闭锁可以延迟线程的进度直到其到达终止状态,闭锁可以用来确保某些活动直到其他活动都完成才继续执行:

(1)确保某个计算在其需要的所有资源都被初始化之后才继续执行。
(2)确保某个服务在其依赖的所有其他服务都已经启动之后才启动。
(3)等待直到某个操作的所有参与者都就绪再继续执行。

需求1:计算10个学生抢苹果的总时间

(1)代码实现:

public class NoCountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        long begin = System.currentTimeMillis();
        Apple apple = new Apple();
        for (int i = 0; i < 10; i++) {
            new Thread(apple).start();
        }

        long end = System.currentTimeMillis();
        System.out.println("共耗费" + (end - begin) + "ms时间");

    }
}

class Apple implements Runnable {
    private int appleNum = 100;

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            synchronized (this) {
                if (appleNum > 0) {
                    System.out.println(Thread.currentThread().getName() + "抢到第" + appleNum-- + "个苹果");
                }
            }
        }
    }
}

(2)运行结果:
在这里插入图片描述
(3)问题分析:

耗费总时间应该是苹果抢完之后才计算出来的,现在还在抢的过程中就计算出来了,所以我们需要在计算消耗时间之前设置一个关卡,判断抢苹果线程是否都结束,如果都结束了就执行时间的计算。
在这里插入图片描述
(4)优化后的代码:

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(10);        
        long begin = System.currentTimeMillis();

        Apple1 apple = new Apple1(latch);
        for (int i = 0; i < 10; i++) {
            new Thread(apple).start();
        }

        latch.await();//不让main线程往下运行,直到吃苹果线程都运行完毕,才放行

        long end = System.currentTimeMillis();
        System.out.println("共耗费"+(end-begin)+"ms时间");
    }
}

class Apple1 implements Runnable{
    private int appleNum = 100;
    private CountDownLatch latch;

    public Apple1(CountDownLatch latch) {
        this.latch = latch;
    }
    @Override
    public void run() {

        try {
            for (int i = 0; i < 1000; i++) {
                synchronized (this) {
                    if (appleNum>0) {
                        System.out.println(Thread.currentThread().getName()+"抢到第"+appleNum--+"个苹果");
                    }
                }
            }
        } finally {//必须要执行
            latch.countDown();
        }
    }
}

需求2:10个运动员准备赛跑,他们等待裁判一声令下就开始同时跑,当最后一个人通过终点的时候,比赛结束。

代码实现:

public class CountDownLatchDemo2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(10);

        long beginTime = System.currentTimeMillis();

        Sportsman sportsman = new Sportsman(begin, end);
        for (int i = 0; i < 10; i++) {
            new Thread(sportsman).start();
        }

        Thread.sleep(3000);//起跑线上等待3秒,3,2,1

        begin.countDown(); // 裁判一声令下开始跑

        end.await();// 所有选手到达终点
        long endTime = System.currentTimeMillis();
        System.out.println("共耗费" + (endTime - beginTime) + "ms时间");
    }
}

class Sportsman implements Runnable {

    private CountDownLatch begin;
    private CountDownLatch end;

    public Sportsman(final CountDownLatch begin, final CountDownLatch end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + "预备起跑");
            begin.await();// 等待所有线程准备完毕
            System.out.println(Thread.currentThread().getName() + "跑步中");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName() + "到达终点");
            end.countDown();// 终点计数器,减一
        }
    }
}

参考自链接: https://www.jianshu.com/p/0f4765251b2a
非常感谢!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值