CountDownLatch
CountDownLatch是一种java.util.concurrent包下一个同步工具类,官方的介绍如下
- A synchronization aid that allows one or more threads to wait until
- a set of operations being performed in other threads completes.
大概意思是:它允许一个或多个线程等待直到其他线程中一组操作执行完成。
CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成了任务,在CountDownLatch上等待的线程就可以恢复执行接下来的任务。
解析
下面,我们来看一下CountDownLatch 的源码
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;
}
}
}
private final Sync sync;
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public void countDown() {
sync.releaseShared(1);
}
public long getCount() {
return sync.getCount();
}
public String toString() {
return super.toString() + "[Count = " + sync.getCount() + "]";
}
}
可以看到CountDownLatch只有一个构造方法,就是下面这个,参数是一个int类型的数值,并且不能少于0,少于0就抛出异常。这个count就是计数器的总数,我们必须调用count次的countDown方法,才能让await方法pass通行
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
await方法的作用就是让调用该方法的当前线程进入wait等待状态,直到count被减到0,该线程才会继续执行。如果当前计数为0,则该方法立即返回。
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
这个await方法比普通的await方法多了两个参数,第一个是timeout的时间,第二个是时间单位。
这个方法和普通await方法的区别就是如果过了timeout时间,但是count还不为0的时候,会让调用方法的线程继续执行下来,而不是等待
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
让count值减1,当线程执行完我们想要执行的代码后,我们就会调用countDown方法
public void countDown() {
sync.releaseShared(1);
}
获取当前的count值
public long getCount() {
return sync.getCount();
}
例子
以下是一个简单的例子:让所有子线程执行完后,再让主线程执行
public class CountdownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(3);
final CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
Thread.sleep((long) (Math.random() * 1000));
System.out.println("子线程"+Thread.currentThread().getName()+"执行完成");
//执行完成,调用countDown方法,count减1
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
}
try {
System.out.println("主线程"+Thread.currentThread().getName()+"等待子线程执行完成...");
//阻塞当前线程,直到计数器的值为0
latch.await();
System.out.println("主线程"+Thread.currentThread().getName()+"开始执行...");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
service.shutdown();
}
}
}
运行结果: