多线程之CountDownLatch

多线程之CountDownLatch

A latch is a synchronizer that can delay the progress of threads until it reaches its terminal state [

A latch acts as a gate: until the latch reaches the terminal state the gate is closed and no thread can pass, and in the terminal state the gate opens, allowing all threads to pass.

Latches can be used to ensure that certain activities do not proceed until other one-time activities complete, such as:

img

Using a starting gate allows the master thread to release all the worker threads at once, and the ending gate allows the master thread to wait for the last thread to finish rather than waiting sequentially for each thread to finish.


CountDownLatch的作用是让线程等待其它线程完成一组操作后才能执行,否则就一直等待。

举个开会的例子:

  1. 老板先进入会议室准备材料
  2. 等待5个员工陆续进入会议室
  3. 员工到齐开始开会

publicclass CountDownLatchTest {
privatestatic CountDownLatch countDownLatch = new CountDownLatch(5);

// Boss线程,等待员工到齐开会
staticclass BossThread extends Thread {
@Override
public void run() {
System.out.println("Boss进入会议室准备材料...");
System.out.println("Boss在会议室等待...");
try {
countDownLatch.await(); // Boss等待
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Boss等到人齐了,开始开会...");
}
}

// 员工到达会议室
staticclass EmpleoyeeThread extends Thread {
@Override
public void run() {
System.out.println("员工" + Thread.currentThread().getName()
+ ",到达会议室....");
countDownLatch.countDown();
}
}

public static void main(String[] args) {
// Boss线程启动
new BossThread().start();

// 员工到达会议室
for (int i = 0; i < countDownLatch.getCount(); i++) {
new EmpleoyeeThread().start();
}
}
}

https://mp.weixin.qq.com/s?__biz=MzAxMjEwMzQ5MA==&mid=2448890657&idx=2&sn=f15b9128abdc1342b6ba6779004ecf8c&scene=21#wechat_redirect