简单介绍
CountDownLatch的通常用法和Thread.join()有点类似,等待其它线程都完成后再执行主任务。允许一个或多个线程等待其它线程的操作执行完毕后再执行后续的操作。先看看怎么用:
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(()->{
try {
System.out.println("Aid thread is waiting for starting.");
startSignal.await();
// do sth
System.out.println("Aid thread is doing something.");
doneSignal.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
// main thread do sth
Thread.sleep(2000);
System.out.println("Main thread is doing something.");
startSignal.countDown();
// main thread do sth else
System.out.println("Main thread is waiting for aid threads finishing.");
doneSignal.await();
System.out.println("Main thread is doing something after all threads have finished.");
}
}
上述代码中存在两个CountDownLatch,主线程控制startSignal,5个子线程等待主线程完成任务之后开始执行。并等待五个子线程分别完成之后再继续执行主线程的执行逻辑。
内部类
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) {
// 注意,这里state等于0的时候返回的是1,也就是说count减为0的时候获取总是成功
// state不等于0的时候返回的是-1,也就是count不为0的时候总是要排队
return (getState() == 0) ? 1 : -1;
}
// 尝试释放锁
protected boolean tryReleaseShared(int releases) {
for (;;) {
// state的值
int c = getState();
// 等于0了,则无法再释放了
if (c == 0)
return false;
// 将count的值减1
int nextc = c-1;
// 原子更新state的值
if (compareAndSetState(c, nextc))
// 减为0的时候返回true,这时会唤醒后面排队的线程
return nextc == 0;
}
}
}
CountDownLatch内部使用AQS来控制并发,Sync重写了tryAcquireShared()和tryReleaseShared()方法,并把count存到state变量中去。上面两个方法的参数没有真正的作用。
构造函数
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
CountDownLatch的构造函数较为简单,仅传递控制量的大小即可。
重要方法
await方法
// java.util.concurrent.CountDownLatch.await()
public void await() throws InterruptedException {
// 调用AQS的acquireSharedInterruptibly()方法
sync.acquireSharedInterruptibly(1);
}
// java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly()
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
// 尝试获取锁,如果失败则排队
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
await()方法是等待其它线程完成的方法,它会先尝试获取一下共享锁,如果失败则进入AQS的队列中排队等待被唤醒。根据上面Sync的源码,我们知道,state不等于0的时候tryAcquireShared()返回的是-1,也就是说count未减到0的时候所有调用await()方法的线程都要排队。
countDown()方法
// java.util.concurrent.CountDownLatch.countDown()
public void countDown() {
// 调用AQS的释放共享锁方法
sync.releaseShared(1);
}
// java.util.concurrent.locks.AbstractQueuedSynchronizer.releaseShared()
public final boolean releaseShared(int arg) {
// 尝试释放共享锁,如果成功了,就唤醒排队的线程
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
countDown()方法,会释放一个共享锁,也就是count的次数会减1。当其减为0的时候返回true,这时候才会唤醒等待的线程。
总结
CountDownLatch表示允许一个或多个线程等待其它线程的操作执行完毕后再执行后续的操作,其内部使用AQS的共享锁机制实现。CountDownLatch初始化的时候需要传入次数count,每次调用countDown()方法count的次数减1,减为0的时候会唤醒排队着的线程。
标签:count,int,await,util,concurrent,线程,CountDownLatch,public From: https://blog.csdn.net/sinat_35426920/article/details/141141608