Java 闭锁 CountDownLatch

使用例子

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class Main {

    private static CountDownLatch startGate = new CountDownLatch(1);
    private static CountDownLatch endGate = new CountDownLatch(10);

//    countDown方法,当前线程调用此方法,则计数减一
//    awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0

    public static void main(String[] args) throws IOException, InterruptedException {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                System.out.println("this is a test");
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        // 全部阻塞等待startGate变为0
                        startGate.await();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        // 完成任务,endGate减1
                        endGate.countDown();
                    }
                }
            };
            thread.start();
        }
        long start = System.nanoTime();
        // 唤醒所有阻塞的线程,startGate变为0
        startGate.countDown();
        // 阻塞等待直至endGate变为0
        endGate.await();
        long end = System.nanoTime();
        System.out.println(end - start);
    }
}

源码分析

    // 继承自AQS
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        int getCount() {
            return getState();
        }

        // 获取锁条件检查
        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }

        // 释放锁条件检查:自旋等待,直到c==0
        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;
            }
        }
    }

    private final Sync sync;
    ...

    // 当countdown次数没到0的时候,所有线程调用都会阻塞在这个函数
    public void await() throws InterruptedException {
        // 获取锁,否则for自旋,直到获取到锁
        sync.acquireSharedInterruptibly(1);
    }

    // 使得当前计数为递减,减到0的时候,会唤醒别的线程调用
    public void countDown() {
        // 不断调用sync释放锁进行检查,直到为0释放锁
        sync.releaseShared(1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值