CountDownLatch的中文翻译为"闭锁",在JDK1.5中 CountDownLatch类加入进来。为程序猿进行并发编程提供有利的帮助。
首先我们先看看JDK文档中对于CountDownLatch类的介绍:
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
大致意思是CountDownLatch为一个同步辅助工具,让一个或多个线程等待,直到其他的线程执行操作完成。
它的功能可以在绝大部分情况上替代join()方法,甚至在实际运用中比join()方法的用法更灵活。
操作过程:用CountDownLatch类创建实例,指定需要等待完成点个数。await()方法会阻塞当前线程,直到计数器减为零。每次线程执行调用countDown()方法,就会使计数器减1,直到计数器减为0时,等待的线程继续运行。
- CountDownLatch类中的构造器:
/**
* Constructs a {@code CountDownLatch} initialized with the given count.
*
* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
* 构造器用给定计数作为参数进行初始化,若参数为负则抛出非法参数异常。
*
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
- CountDownLatch类中的方法:
1. await() 方法
/**
* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
* 使当前线程等待直到闭锁的计数器为0,除非线程由于中断异常中断。
*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
2. await(long timeout, TimeUnit unit) 方法
/**
* Causes the current thread to wait until the latch has counted down to
* zero, unless the thread is {@linkplain Thread#interrupt interrupted},
* or the specified waiting time elapses.
* 使当前线程等待直到闭锁计数器为0,除非线程遇到线程中断异常中断,或者超出指定的等待时间。
* @param timeout the maximum time to wait 超出的最大等待时间
* @param unit the time unit of the {@code timeout} argument 指定最大等待时间的时间单位
* @return {@code true} if the count reached zero and {@code false}
* if the waiting time elapsed before the count reached zero
* @throws InterruptedException if the current thread is interrupted
* while waiting
*/
public boolean await(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
3. countDown() 方法
/**
* Decrements the count of the latch, releasing all waiting threads if
* the count reaches zero.
* 减少闭锁的计数,若计数达到0则释放所有等待线程
* <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);
}
4. getCount() 方法
/**
* Returns the current count.
* 返回当前计数器的值
* <p>This method is typically used for debugging and testing purposes.
*
* @return the current count
*/
public long getCount() {
return sync.getCount();
}
应用:
有这么一道题:用4个线程并发执行从1加到100,每个线程只能加25个数,主线程需要等待子线程结束完成后才能结束。
思想:可以用join()方法,也可以用CountDownLatch对象来暂停主线程。
代码:
import java.util.concurrent.CountDownLatch; public class Compute {
public static int sum = 0;// 存储1加到100的数
public static CountDownLatch count = new CountDownLatch(4);// 闭锁,计数器设置为4 static class ComputeThread extends Thread {// 内部类
int start, end;// 起始与结束 public ComputeThread(int start, int end) {
this.start = start;
this.end = end;
} @Override
public void run() {// 每个线程都进行累加
for (int i = start; i <= end; i++) {
sum += i;
}
System.out.println(currentThread().getName() + ":" + sum);
count.countDown();
}
} public static void main(String[] args) throws InterruptedException {
// 建立4个线程
ComputeThread c1 = new Compute.ComputeThread(1, 25);
ComputeThread c2 = new Compute.ComputeThread(26, 50);
ComputeThread c3 = new Compute.ComputeThread(51, 75);
ComputeThread c4 = new Compute.ComputeThread(76, 100);
// 启动4个线程
c1.start();
c2.start();
c3.start();
c4.start();
// 让调用线程停止,等待计数器为0
count.await();
System.out.println(sum);
}
}