使用概述
CountDownLatch允许一个或多个线程等待其他线程完成操作。
CountDownLatch的构造函数接收一个整型参数作为计数器,如果需要等待N个线程完成,则传入N。
当调用CountDownLatch的countdown方法时,N就会减1,CountDownLatch的await方法会阻塞当前线程,直到N变成0。通过CountDownLatch的await方法和countdown方法的配合,我们可以让某个线程在其他N个线程执行完毕后再执行自身任务,类似于join的功能。
以下是简单的代码示例:
public class Driver {
private final static int N = 5;
//startSignal的作用是让主线程完成work1后,其他子线程再执行任务
private final CountDownLatch startSignal = new CountDownLatch(1);
//doneSignal的作用是让子线程都完成任务后,再执行主线程的work2任务
private final CountDownLatch doneSignal = new CountDownLatch(N);
public void drive() throws InterruptedException {
for (int i = 0; i < N; ++i) {
new Thread(new Worker(startSignal, doneSignal)).start();
}
doWork1();
startSignal.countDown(); // let all threads proceed
doneSignal.await(); // wait for all to finish
doWork2();
}
private void doWork1() {
try {
System.out.printf("%s doWork1 start:%d%n", Thread.currentThread().getName(), System.currentTimeMillis());
Thread.sleep(new Random().nextInt(5000));
System.out.printf("%s doWork1 end:%d%n", Thread.currentThread().getName(), System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doWork2() {
try {
System.out.printf("%s doWork2 start:%d%n", Thread.currentThread().getName(), System.currentTimeMillis());
Thread.sleep(new Random().nextInt(5000));
System.out.printf("%s doWork2 end:%d%n", Thread.currentThread().getName(), System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Driver driver = new Driver();
driver.drive();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
@Override
public void run() {
try {
startSignal.await();
doWork();
doneSignal.countDown();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
private void doWork() {
try {
System.out.printf("%s start:%d%n", Thread.currentThread().getName(), System.currentTimeMillis());
Thread.sleep(new Random().nextInt(5000));
System.out.printf("%s end:%d%n", Thread.currentThread().getName(), System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
源码分析
(1) 数据结构
CountDownLatch只有一个sync的属性,sync的类型是CountDownLatch内部类Sync同步器,Sync继承自AQS,CountDownLatch正是通过该同步器实现
相应的线程同步功能,其源码如下:
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;
}
}
}
(2) 核心方法
构造函数
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
//count即为共享变量state的值
this.sync = new Sync(count);
}
await()
await()
方法可以阻塞当前线程,直到共享变量state的值为0,另外还有一个await(long timeout, TimeUnit unit)
重载方法,可以指定超时时间,这里只以await()
为例进行分析。
await()
方法源码如下:
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
其内部调用了AQS的acquireSharedInterruptibly(int arg)
方法,该方法会响应中断。
接着调用CountDownLatch的内部同步器Sync的tryAcquireShared(int arg)
方法,当state不为0时,tryAcquireShared返回-1,此时才会执行AQS的doAcquireSharedInterruptibly(int arg)
方法。
doAcquireSharedInterruptibly
的作用为,当state不为0时,线程会在同步队列中排队阻塞,当state为0时,线程会被唤醒开始执行任务。
//class: AbstractQueuedSynchronizer
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//当state为0时,tryAcquireShared返回1;
//当state不为0时,tryAcquireShared返回-1;
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
//class: AbstractQueuedSynchronizer
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) {
//如果state为0时,r为1,意味着同步队列中的结点可以被唤醒开始执行任务
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
//在同步队列中排队阻塞
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
countdown()
countdown方法类似与释放一个锁,调用了AQS的releaseShared(int args)
方法,该方法一般用于释放共享锁。
public void countDown() {
sync.releaseShared(1);
}
tryReleaseShared(int arg)
调用的是CountDownLatch的同步器Sync的实现,主要作用是将共享变量减1,然后返回state是否为0,state为0就可以唤醒同步队列中的线程。
//class: AbstractQueuedSynchronizer
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}