JAVA线程同步辅助类CountDownLatch

时间:2023-12-11 15:57:02

一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier

CountDownLatch 是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待。用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。

CountDownLatch 的一个有用特性是,它不要求调用 countDown 方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,它只是阻止任何线程继续通过一个 await

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* 倒计时 countdownlatch
* @author duwenlei
*
*/
public class CountDownLatchTest { public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch subLatch = new CountDownLatch(1); //运动员的
final CountDownLatch mainLatch = 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()+"准备待命");
subLatch.await(); //运动员等待裁判发出口令
System.out.println("线程"+Thread.currentThread().getName()+"已经收到命令"); Thread.sleep(new Random().nextInt(10000));
System.out.println("线程"+Thread.currentThread().getName()+"线程已完成"); //已经跑完
mainLatch.countDown(); //通知裁判
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
service.execute(runnable);
} try {
Thread.sleep(new Random().nextInt(10000));
System.out.println("线程"+Thread.currentThread().getName()+"即将发送命令"); //发出口令,3个线程开始跑步
subLatch.countDown(); //计数器减一 System.out.println("线程"+Thread.currentThread().getName()+"正在等待结果"); //口令发出后等待结果
mainLatch.await(); //等待所有跑完 System.out.println("线程"+Thread.currentThread().getName()+"已收到所有响应");
} catch (InterruptedException e) {
e.printStackTrace();
}
service.shutdown();
} }