JUC并发包—CountDownLatch

目录

什么是CountDownLatch

CountDownLatch的方法

例子

CountDownLatch的实现原理

countDown方法源码

await方法源码


什么是CountDownLatch

CountDownLatch是JDK提供的一个同步工具,它可以让一个或多个线程等待,一直等到其他线程中执行完成一组操作。可以用作线程同步

CountDownLatch的方法

countDown方法

CountDownLatch在初始化时,需要给构造器指定用给定一个整数作为计数器。

CountDownLatch countDownLatch = new CountDownLatch(10);

当调用countDown方法时,计数器会被减1

await方法

当调用await方法时,如果计数器大于0时,线程会被阻塞,一直到计数器被countDown方法减到0时,线程才会继续执行。计数器是无法重置的,当计数器被减到0时,调用await方法都会直接返回。

例子

实现类型LOL十个玩家加载完成后,开始游戏

public class Countdown_Latch {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(10);
        String[] all = new String[10];
        Random r = new Random();

        for (int j = 0; j <10 ; j++) {
            int a = j;
            pool.submit(()->{
                for (int i = 0; i <=100 ; i++) {
                    all[a] = i+"%";
                    try {
                        Thread.sleep(r.nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.print("\r"+Arrays.toString(all));  
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("\n"+"游戏开始");
        pool.shutdown();     
    }

}

//输出结果

[100%, 100%, 100%, 100%, 100%, 100%, 100%, 100%, 100%, 100%]
游戏开始

CountDownLatch的实现原理

CountDownLatch有一个内部类叫做Sync,它继承了AbstractQueuedSynchronizer类,其中维护了一个整数state,并且保证了修改state的可见性和原子性。

public CountDownLatch(int count) {
    if (count < 0) throw new IllegalArgumentException("count < 0");
    this.sync = new Sync(count);
}

countDown方法源码

在 countDown方法中,只调用了Sync实例的releaseShared方法

public void countDown() {
    sync.releaseShared(1);
}

其中的releaseShared方法,先对计数器进行减1操作,如果减1后的计数器为0,唤醒被await方法阻塞的所有线程。

public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {  //对计数器进行减一操作
        doReleaseShared();        //如果计数器为0,唤醒被await方法阻塞的所有线程
        return true;
    }
    return false;
}

await方法源码

await方法中,只调用了Sync实例的acquireSharedInterruptibly方法

public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}

其中acquireSharedInterruptibly方法,判断计数器是否为0,如果不为0则阻塞当前线程

public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    if (tryAcquireShared(arg) < 0)        //判断计数器是否为0
        doAcquireSharedInterruptibly(arg);//如果不为0则阻塞当前线程
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值