0%

深入理解CountDownLatch

CountDownLatch基于AQS的共享模式,用来控制一个或者多个线程等待多个线程

CountDownLatch使用一个计数器进行实现。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。

使用案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Demo1 {

public static void main(String[] args) throws InterruptedException {
int nCore = Runtime.getRuntime().availableProcessors() * 2;
int nQueue = 10;
ExecutorService executorService = new ThreadPoolExecutor(nCore, nCore,
0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(nQueue),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
CountDownLatch master = new CountDownLatch(1);
CountDownLatch worker = new CountDownLatch(nQueue);
for (int i = 0; i < nQueue; i++) {
executorService.execute(() -> {
try {
master.await();
System.out.println(Thread.currentThread().getName() + " arrive");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
worker.countDown();
}
});
}
master.countDown();
worker.await();
System.out.println("main");
executorService.shutdown();
}
}
1
2
3
4
5
6
7
8
9
10
11
pool-1-thread-7 arrive
pool-1-thread-10 arrive
pool-1-thread-2 arrive
pool-1-thread-3 arrive
pool-1-thread-9 arrive
pool-1-thread-1 arrive
pool-1-thread-4 arrive
pool-1-thread-8 arrive
pool-1-thread-6 arrive
pool-1-thread-5 arrive
main

构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;

Sync(int count) {
setState(count); // 用的是AQS中的state
}
// 重写了AQS中的方法:尝试获取共享资源
protected int tryAcquireShared(int acquires) {
// 当状态为0,则该线程获取到该共享锁
// 刚开始肯定state被设置成count,所以肯定获取失败,只有当所有线程释放了锁(countDown)才能获取到
return (getState() == 0) ? 1 : -1;
}
// 重写了AQS中的方法:尝试释放共享资源
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
// 减少count,当检测到状态值为0时,通知同步队列中被挂起的线程
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}

await方法

调用了AQS中的doAcquireSharedInterruptiblydoAcquireSharedInterruptiblydoAcquireShared很相似,主要区别是doAcquireSharedInterruptibly响应中断(抛出InterruptedException异常),而doAcquireShared不响应中断(记录中断,最后再selfInterrupt())。

只要共享锁状态值不为0,则请求共享锁的线程均会添加到同步队列中,阻塞挂起,等待被通知。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
// 重写了AQS中的方法:尝试获取共享资源
protected int tryAcquireShared(int acquires) {
// 当状态为0,则该线程获取到该共享锁
// 刚开始肯定state被设置成count,所以肯定获取失败,只有当所有线程释放了锁(countDown)才能获取到
return (getState() == 0) ? 1 : -1;
}

那这些被阻塞挂起的线程啥时候会被唤醒继续执行呢?答案就在countDown方法中

countDown方法

释放一个资源,当检测到状态值为0时,通知同步队列中被挂起的线程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Decrements the count of the latch, releasing all waiting threads if
* the count reaches zero.
*
* <p>If the current count is greater than zero then it is decremented.
* If the new count is zero then all waiting threads are re-enabled for
* thread scheduling purposes.
*
* <p>If the current count equals zero then nothing happens.
*/
public void countDown() {
sync.releaseShared(1); // 释放一个资源
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();// doReleaseShared会唤醒同步队列中阻塞挂起的线程
return true;
}
return false;
}
// 重写了AQS中的方法:尝试释放共享资源
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;
// CAS减少count
if (compareAndSetState(c, nextc))
return nextc == 0; // 当检测到状态值为0时,通知同步队列中被挂起的线程
}
}

唤醒后的线程会进行获取锁的操作。当状态值归零后,由于tryReleaseShared恒返回1,代表任何线程均可以获取共享锁成功。

也就是说:CountDownLatch是一次性的,在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用

坚持原创技术分享,您的支持将鼓励我继续创作!