栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【JUC】CountDownLatch

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【JUC】CountDownLatch

CountDownLatch
  • 一、概述
    • 1.1 案例
    • 代码
    • 解决方案

一、概述

CountDownLatch允许一个或多个线程等待其他线程完成操作。

1.1 案例

假设由50个线程,有一个原子类AtomicInteger,50个线程都对该类进行自增1000次

代码
public class AtomicDemo {
    static AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    atomicInteger.incrementAndGet();
                }
            },String.valueOf(i)).start();

        }
        System.out.println(Thread.currentThread().getName() + atomicInteger.get());
    }
}

如果执行上面的代码会出现结果不对的情况,原因就是main线程打印结果时,50个线程自增的操作还未执行完。

解决方案

使用CountDownLatch进行计数,知道50个线程都完成自增操作之后,再进行打印结果操作

public class AtomicDemo {
    static AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(50);
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {

                try {
                    for (int j = 0; j < 1000; j++) {
                        atomicInteger.incrementAndGet();
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }

            },String.valueOf(i)).start();

        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + atomicInteger.get());
    }
}

此时我们就不会出现结果不正确的情况了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/606035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号