hooyantsing's Blog

15_CountDownLatch

字数统计: 158阅读时长: 1 min
2020/08/26

15 CountDownLatch

狂神说Java JUC并发编程最新版通俗易懂

当需要多个线程的业务执行完毕后再向下执行,可以使用 CountDownLatch

减法计数器

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package add;

import java.util.concurrent.CountDownLatch;

/**
* 当需要多个线程的业务执行完毕后再向下执行,可以使用 CountDownLatch
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// 减数计数器
CountDownLatch countDownLatch = new CountDownLatch(6);

for (int i = 0; i < 6; i++) {
new Thread(
() -> {
System.out.println(Thread.currentThread().getName() + "GO");
// -1
countDownLatch.countDown();
}
).start();
}

// 等待计数器归零然后再向下执行。
countDownLatch.await();
System.out.println("Close Door");
}
}
CATALOG
  1. 1. 15 CountDownLatch
    1. 1.0.1. 案例