介绍
一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier。
CountDownLatch 是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待。用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。
CountDownLatch 的一个有用特性是,它不要求调用 countDown 方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,它只是阻止任何线程继续通过一个 await。
示例
package com.chen.concurrent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatchTest countDownLatchTest = new CountDownLatchTest();
AtomicInteger atomicInteger = new AtomicInteger(100);
try {
countDownLatchTest.test01(2,atomicInteger);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void test01(int t_number,AtomicInteger workTask) throws InterruptedException{
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(t_number);
Worker worker = new Worker(startSignal, doneSignal,workTask);
for(int i = 0;i < t_number;i++){
Thread thread = new Thread(worker);
thread.start();
}
startSignal.countDown();
System.out.println("工作开始===========");
doneSignal.await();
System.out.println("工作结束===========");
}
class Worker implements Runnable{
private CountDownLatch startSignal;
private CountDownLatch doneSignal;
private AtomicInteger workTask;
public Worker(CountDownLatch startSignal,CountDownLatch doneSignal,AtomicInteger workTask) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
this.workTask = workTask;
}
@Override
public void run() {
try {
startSignal.await();
doWork();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doWork(){
System.out.println(Thread.currentThread().getName()+"开始工作");
while(workTask.get() != 0){
int result = workTask.decrementAndGet();
System.out.println(Thread.currentThread().getName()+":"+result);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"工作结束");
doneSignal.countDown();
}
}
}