什么是 JUC
JUC 就是 java.util.concurrent 包,这个包俗称 JUC,里面都是解决并发问题的一些东西。该包的位置位于 java 下面的 rt.jar 包下面。4大常用并发工具类:CountDownLatch、CyclicBarrier、Semaphore、ExChanger。
CountDownLatch:CountDownLatch, 俗称闭锁,作用是类似加强版的 Join, 是让一组线程等待其他的线程完成工作以后才执行,就比如在启动框架服务的时候,我们主线程需要在环境线程初始化完成之后才能启动,这时候我们就可以实现使用 CountDownLatch 来完成。
/**
* Constructs a {@code CountDownLatch} initialized with the given count.
*
* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
在源码中可以看到,创建 CountDownLatch 时,需要传入一个 int 类型的参数,将决定在执行次扣减之后,等待的线程被唤醒