14 countDownlanch实现原理

vvEcho 2025-03-01 14:11:31
Categories: Tags:

总结
CountDownLatch是基于AQS实现,内部维护了一个state的计数器,await() 会在state不为 0 时阻塞线程,countDown() 通过 CAS 减少 state,当 state 为 0 时,通过 AQS 唤醒所有等待线程;

底层实现为提供一个常量类继承AQS实现的

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
34
public class CountDownLatch {
/**
* Synchronization control For CountDownLatch.
* Uses AQS state to represent count
*/
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;
}

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;
}
}
}
// 其他代码省略
}

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* countdownlatch 让线程同时执行
* @auther: echo
* @date: 2025/3/1
*/
public class CountDownLatchTest {

public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
countDownLatch.await();
System.out.println(System.currentTimeMillis());

} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
countDownLatch.countDown();
}
}