文章目录
1.CountDownLatch介绍
CountDownLatch直译为倒计时锁,也称为闭锁.参考源码中类上的注释大体意思就是
CountDownLatch是一种同步辅助程序,允许一个或多个线程等待在其他线程中执行的一组操作完成.
使用给定的count来初始化CountDownLatch,由于CountDownLatch使用了倒计时的方式,调用await方法后会阻塞住,直到count为0才会释放所有等待的线程.并立即返回至await开始后续执行.没有提供重置的方法,只要count为0,就是执行结束.
1.1.使用场景
适用于多线程中线程有先后顺序的场景.如:
- 多个线程同时执行,在所有线程执行完成后,主线程还需要后续操作的情况.
- 多个线程中,部分线程需要在一些线程执行之后才能开始执行的情况.
1.2.与CyclicBarrier的区别
CountDownLatch只能使用一次,所有使用await阻塞的线程,在同步状态state变为0时候回被唤醒,之后await失去作用。
CyclicBarrier如果创建传入的对象参数是n,则保证都阻塞在await的位置,直到n个线程都执行到await的位置,才会放开线程继续执行。如果有m个线程在执行(m远大于n),则每次只能有n个线程执行,其他还是阻塞状态,直到下一次到达n个线程才会放开线程继续执行。
1.3.用法
场景:在所有线程执行完成后,打印所有线程执行的总时间
使用方式:如果有n个线程,将CountDownLatch初始值为n,每个线程执行结束就使用countDown方法进行计数减1,主线程使用await阻塞直到计数为0,打印总时间.
测试代码如下:
public static void main(String[] args) throws InterruptedException {
int threads = 5;//创建线程数
CountDownLatch signal = new CountDownLatch(threads);
long start = System.currentTimeMillis();
for (int i = 0; i < threads; i++) {
final int j = i;
new Thread(() -> {
Thread.currentThread().setName("Thread " + j);
System.out.println(Thread.currentThread().getName() + " exec dowork");
try {
Thread.sleep(j * 1000);
System.out.println(Thread.currentThread().getName() + "is end");
} catch (InterruptedException e) {
e.printStackTrace();
}
signal.countDown();//线程执行完成计数减1
}).start();
}
//等待所有线程执行完成
signal.await();
//主线程计算总时间
System.out.println(String.format("所有线程执行完成所需时间: %s ms",(System.currentTimeMillis()-start)));
}
2.使用的知识点
主要依赖于AQS框架,用到的技术点也都在AQS中,详情可参考ReentrantLock源码分析中介绍的知识点.
3.数据结构
相关类图如下:
其使用内部类sync继承AQS,并且重写tryAcquireShared和tryReleaseShared来设置共享锁和释放共享锁.
4.执行流程
CountDownLatch主要分为两个过程,阻塞过程await()和计数递减及释放过程countDown()
4.1.await()过程分析
4.1.1.执行流程图
4.1.2.源码执行流程
如下:
CountDownLatch类中await()如下:
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);//通过Sync调用AQS中的acquireSharedInterruptibly
}
acquireSharedInterruptibly源码如下:
public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())//线程如果处于中断状态直接返回
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)//调用Sync类获取共享锁
//以共享可中断模式获取
doAcquireSharedInterruptibly(arg);
}
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);//以共享模式加入等待队列的队尾
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
//如果前驱节点是队列头节点head,尝试获取共享锁
int r = tryAcquireShared(arg);
if (r >= 0) {//r大于0获取锁成功
setHeadAndPropagate(node, r);//将当前节点设置为头节点head,并且释放锁
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) //获取锁失败的节点检查并更新状态,第一次循环到此处会将状态设置为SIGNAL并且返回false,第二次循环到此返回true
&& parkAndCheckInterrupt())//设置线程阻塞park并检查线程是否中断,第二次循环进来会使用park阻塞当前线程
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//加入等待队列
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
//阻塞线程
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);//阻塞线程
return Thread.interrupted();
}
//将节点node设置为队列头节点,根据状态判断是否唤醒线程
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);
/*
* Try to signal next queued node if:
* Propagation was indicated by caller,
* or was recorded (as h.waitStatus either before
* or after setHead) by a previous operation
* (note: this uses sign-check of waitStatus because
* PROPAGATE status may transition to SIGNAL.)
* and
* The next node is waiting in shared mode,
* or we don't know, because it appears null
*
* The conservatism in both of these checks may cause
* unnecessary wake-ups, but only when there are multiple
* racing acquires/releases, so most need signals now or soon
* anyway.
*/
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
if (s == null || s.isShared())
doReleaseShared();//唤醒线程
}
}
//唤醒线程
private void doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);//唤醒线程
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
Sync类如下:
//尝试获取共享锁,state为0,则获取成功返回1
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
4.2.countDown()过程分析
4.2.1执行流程图
4.2.2.源码执行流程
CountDownLatch中countDown方法如下:
public void countDown() {
sync.releaseShared(1);//通过Sync调用AQS中的acquireSharedInterruptibly
}
AQS中releaseShared方法如下:
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {//调用Sync类将计数器减1,并返回是否获取到锁
//如果获取到共享锁,则唤醒等待队列中所有的阻塞线程
doReleaseShared();//此方法源码前面已介绍
return true;
}
return false;
}