当前位置:网站首页>Usage of countdownlatch in multithreaded environment
Usage of countdownlatch in multithreaded environment
2022-07-27 15:12:00 【James-Tom】
1、 summary
Google literal translation : countdown
There are other translations : Count down latch , Countdown latch
CountDownLatch The package path where the class is located : java.util.concurrent.CountDownLatch
A synchronous auxiliary class , It allows one or more threads to wait , Until a set of operations performed in other threads is complete .
Use scenarios : Create multiple sub threads in the main thread , Wait for all sub threads to complete execution , Then switch to the waiting position of the main thread and continue to execute .
2、 Key methods 、 function
| name | describe |
|---|---|
| await() | Causes the current thread to wait , Until the latch decreases to zero , Unless the thread is interrupted . |
| boolean await(long timeout, TimeUnit unit) | Causes the current thread to wait , Until the latch counts to zero , Unless the thread is interrupted or the specified waiting time has elapsed . |
| countDown() | Reduce the latch count , If the count reaches zero , Then release all waiting threads . |
| long getCount() | Returns the current count . The return value is 0 when , After that, all waiting threads are released , The main thread continues to execute await() After the code . |
3、 Case study
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/** * Created by Administrator on 2020/4/24. */
public class TestCountDownLatch {
private static ExecutorService es = Executors.newCachedThreadPool();
static boolean isRun = false;
public static void main(String[] args) {
startTask();
// If the thread pool is no longer used , You can close the thread pool through the following sentence , Release resources .
//es.shutdown();
}
private static volatile CountDownLatch latchInstance;
private static CountDownLatch getInstance(final int count) {
if (null == latchInstance) {
synchronized (CountDownLatch.class) {
if (null == latchInstance) {
latchInstance = new CountDownLatch(count);
}
}
}
return latchInstance;
}
/** * Start polling task */
private static void startTask() {
int threadNum = 5;
latchInstance = getInstance(threadNum);
for (; ; ) {
//TODO 3、 Key statement by 0, It means that all the sub threads are completed , Will execute .await(); The following statement
if (latchInstance.getCount() == 0) {
//latchInstance It can only be used once , After use, it becomes 0 ; by 0 Then you can't count down anymore , If you want to continue counting down, you need to re instantiate
latchInstance = null;
// When re instantiating, you can set the number of new threads ; Because it is possible to group request scenarios , The first group may only need 5 Threads , In the second round, you only need 3 One thread is enough , Save resources .
latchInstance = getInstance(threadNum);
}
if (!isRun) {
isRun = true;
System.out.println(" The main thread starts executing …… ……");
// Loop rebuild in the main thread threadNum Child threads
for (int i = 0; i < threadNum; i++) {
// Throw sub threads into the thread pool
es.execute(() -> {
try {
Thread.sleep(1000);
System.out.println(" Sub thread :" + Thread.currentThread().getName() + " perform ");
} catch (InterruptedException e) {
e.printStackTrace();
}
//TODO 1、 Key statement Count down the execution completion of sub threads
latchInstance.countDown();
});
}
try {
//TODO 2、 Key statement The code after this sentence ( The main thread ) It will wait for all sub threads to complete before continuing to execute .
latchInstance.await();
isRun = false;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(threadNum + " The sub threads are all executed , Continue to execute the main thread " + isRun);
// for the first time , After the execution of all sub threads , hypothesis : In order to save resources , I reduce the number of threads to 3 individual . This place can do many articles ,threadNum It's a dynamic value , The number of sub threads can be dynamically controlled
threadNum = 3;
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Several key points in the case :
latchInstance.countDown();
The sub thread completes a , Then the counter -1
latchInstance.await();
The code after this sentence , Will wait for all sub threads to complete execution , Will continue to carry on , Otherwise, it will be in a waiting state .
if (latchInstance.getCount() == 0)
If the counter changes to 0, It means that all the sub threads are completed , Will execute latchInstance.await(); The following statement
Output :
The main thread starts executing …… ……
Sub thread :pool-1-thread-1 perform
Sub thread :pool-1-thread-3 perform
Sub thread :pool-1-thread-5 perform
Sub thread :pool-1-thread-4 perform
Sub thread :pool-1-thread-2 perform
5 The sub threads are all executed , Continue to execute the main thread false
The main thread starts executing …… ……
Sub thread :pool-1-thread-5 perform
Sub thread :pool-1-thread-3 perform
Sub thread :pool-1-thread-4 perform
3 The sub threads are all executed , Continue to execute the main thread false
The main thread starts executing …… ……
Sub thread :pool-1-thread-4 perform
Sub thread :pool-1-thread-5 perform
Sub thread :pool-1-thread-3 perform
3 The sub threads are all executed , Continue to execute the main thread false
...
In the case, the singleton mode is used to create CountDownLatch example .
4、 summary
CountDownLatch When creating an instance, the constructor must pass in a number of child threads , And the value of the number of sub threads needs >0.
When getCount() =0 when , At this time, all you see is an ordinary multithreaded environment , Therefore, you need to re pass in the number of sub threads to create a new CountDownLatch example .
边栏推荐
- TCC
- Dynamic programming - stock trading 5
- RS485接口的EMC设计方案
- [ManageEngine] what is Siem
- 移动端使用vantUI的list组件,多个tab项来回切换时,列表加载多次导致数据无法正常展示
- 网络设备硬核技术内幕 路由器篇 (10) CISCO ASR9900拆解 (四)
- LeetCode 341.扁平化嵌套列表迭代器 dfs,栈/ Medium
- Zhou Hongyi: if the digital security ability is backward, it will also be beaten
- LeetCode 191. Number of 1 Bits(位1的个数) 位运算/easy
- The interviewer asked: how to judge whether an element is in the visible area?
猜你喜欢

How to do well in enterprise system vulnerability assessment

【WORK】关于技术架构

Understand the evolution of redis architecture in one article
![[ManageEngine] what is Siem](/img/a6/0fbe60df6bef337a91a10fe046aa8a.jpg)
[ManageEngine] what is Siem

Introduction of the connecting circuit between ad7606 and stm32

SkyWalking分布式系统应用程序性能监控工具-中

AssetBundle如何打包

LeetCode 781. 森林中的兔子 哈希表/数学问题 medium

图解 SQL,这也太形象了吧

Graphical SQL is too vivid
随机推荐
Lesson 3: SPFA seeking the shortest path
STM32之CAN ---CAN ID过滤器分析
An example of building 3D effects on the web based on three.js
数据仓库项目从来不是技术项目
网络设备硬核技术内幕 路由器篇 (10) CISCO ASR9900拆解 (四)
Unity最简洁的对象池实现
事务_基本演示和事务_默认自动提交&手动提交
Introduction of the connecting circuit between ad7606 and stm32
关于印发《深圳市工业和信息化局绿色制造试点示范管理暂行办法》的通知
Get the data of the first frame of unity's open camera
如何帮助企业优化Office管理
Skywalking distributed system application performance monitoring tool - medium
What is tor? What is the use of tor browser update?
初探STM32掉电复位PDR
网络设备硬核技术内幕 路由器篇 21 可重构的路由器
Nefu117 number of prime numbers [prime number theorem]
Wechat applet realizes music search page
STM32F103C8T6在Arduino框架下驱动ssd1306 0.96“ IIC OLED显示
Idea makes jar packages and introduces jar packages
Visual system design example (Halcon WinForm) -10. PLC communication