当前位置:网站首页>Countdownlatch blocking wait for multithreading concurrency
Countdownlatch blocking wait for multithreading concurrency
2022-07-01 17:25:00 【It takes time for fish to find water】
1. brief introduction
CountDownLatch
in count down
It means to count down ,latch
It's the latch 、 The meaning of locking . The whole meaning can be understood as the countdown bolt .CountDownLatch
The same is true of , In the structure CountDownLatch
You need to pass in an integer n( must >0), In this integer “ Reciprocal ” To 0 Before , The main thread needs to wait at the door , And this “ Reciprocal ” The process is driven by each execution thread , Each thread performs a task “ Reciprocal ” once . In conclusion ,CountDownLatch
Wait for other threads to finish their tasks , If necessary, the execution results of each task can be summarized , Then the main thread continues to execute .
CountDownLatch
There are two main ways :countDown()
and await()
.countDown()
Method is used to decrement the counter by one , It's generally a thread call to perform a task ,await()
Method makes the thread calling the method wait , It is generally called by the main thread . What needs to be noted here is ,countDown()
Method does not specify that a thread can only be called once , When the same thread is called multiple times countDown()
When the method is used , Each time, the counter will be decremented by one ; in addition ,await()
Method does not specify that only one thread can execute the method , If multiple threads execute at the same time await()
Method , Then these threads will be in the waiting state , And share the same lock in shared mode .
2. Method API
Method :
Method | explain |
---|---|
await() | Make the current thread enter the synchronization queue to wait , until latch The value of is reduced to 0 Or the current thread is interrupted , The current thread will be awakened . |
await(long timeout, TimeUnit unit) | wait for timeout After time ,count The value of is not yet 0, No more waiting , Then we will continue |
countDown() | send latch The value of the reduction 1 , If it's down to 0 , Will wake up all waiting in this latch On the thread . |
getCount() | get latch The numerical . |
3. Use
3.1 await()
Example :
CountDownLatch count = new CountDownLatch(3);
new Thread(()->{
// Deal with business 1
try {
TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) {
e.printStackTrace(); } finally {
count.countDown();// Ensure that each task is performed in descending order
}
}, "t1").start();
new Thread(()->{
// Deal with business 2
try {
TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {
e.printStackTrace(); } finally {
count.countDown();// Ensure that each task is performed in descending order
}
}, "t2").start();
new Thread(()->{
// Deal with business 3
try {
TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {
e.printStackTrace(); } finally {
count.countDown(); // Ensure that each task is performed in descending order
}
}, "t3").start();
long startTime = System.currentTimeMillis();
count.await(); // Waiting for the task to execute
long endTime = System.currentTimeMillis();
System.out.println(" Task execution completed , Time consuming :" + (endTime - startTime) + " millisecond ");
result :
3.2 boolean await(long timeout, TimeUnit unit)
boolean await(long timeout, TimeUnit unit) Example :
CountDownLatch count = new CountDownLatch(3);
new Thread(()->{
// Deal with business 1
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("task1 over");} catch (InterruptedException e) {
e.printStackTrace(); } finally {
count.countDown();// Ensure that each task is performed in descending order
}
}, "t1").start();
new Thread(()->{
// Deal with business 2
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("task2 over");} catch (InterruptedException e) {
e.printStackTrace(); } finally {
count.countDown();// Ensure that each task is performed in descending order
}
}, "t2").start();
new Thread(()->{
// Deal with business 3
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("task3 over");} catch (InterruptedException e) {
e.printStackTrace(); } finally {
count.countDown(); // Ensure that each task is performed in descending order
}
}, "t3").start();
long startTime = System.currentTimeMillis();
boolean await = count.await(2, TimeUnit.SECONDS);// Specify waiting time , If there are currently tasks that have not been completed, return false
System.out.println(" Whether all tasks have been completed :" + (await ? " yes " : " no "));
System.out.println(" The counter value is :" + count.getCount());
long endTime = System.currentTimeMillis();
System.out.println(" Task execution completed , Time consuming :" + (endTime - startTime) + " millisecond ");
analysis :
Start three threads to execute the task , Mission 1、 Mission 2、 Mission 3 The time-consuming sequence is 1s、2s、3s
Counter await wait for 2s, If 2s The post counter value is not 0( That is, there are three tasks that have not been completed ), So return false. It can be used in some time-consuming tasks , For example, call the third-party interface 、 The business line is relatively long , When the specified time is exceeded, it will be treated as a failure , Avoid that the service is always waiting for blocking .
result :
4. CountDownLatch and Thread.join() Differences in methods
1、
CountDownLatch
One or more threads are allowed to wait for other threads to complete the operation , It looks a bit likejoin()
Method , But it provides more thanjoin()
More flexible API.2、
CountDownLatch
Can be manually controlled in the n Called in a thread n TimecountDown()
Method to make the counter minus one , It can also be called in a threadn Time
Perform minus one operation . andjoin()
The implementation principle of is to keep checking join Is the thread alive , Ifjoin
Thread survival makes the current thread wait forever . So the two are relatively differentCountDownLatch
It is more flexible to use .
5. CountDownLatch Deficiency
CountDownLatch
yes Disposable Of , Calculator values can only be initialized once in a constructor , After that, there is no mechanism to set the value again , When CountDownLatch
After use , It can't be used again .
6. Expand
If you use multithreaded asynchronous tasks Future
, adopt CompletableFuture.allOf
The same effect can be achieved , Block waiting for task execution results , Reference article Multithreading Future,CompletableFuture
边栏推荐
- Openlayers customize bubble boxes and navigate to bubble boxes
- 换掉UUID,NanoID更快更安全!
- 智能运维实战:银行业务流程及单笔交易追踪
- National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report
- Report on research and investment prospects of UHMWPE industry in China (2022 Edition)
- China sorbitol Market Forecast and investment strategy report (2022 Edition)
- 判断二叉树是否为二叉搜索树
- How wild are hackers' ways of making money? CTF reverse entry Guide
- 判断链表是否是回文链表
- 剑指 Offer 20. 表示数值的字符串
猜你喜欢
[flask introduction series] cookies and session
Shenyu gateway development: enable and run locally
可迭代对象与迭代器、生成器的区别与联系
Official announcement! Hong Kong University of science and Technology (Guangzhou) approved!
ACL 2022 | 分解的元学习小样本命名实体识别
【splishsplash】关于如何在GUI和json上接收/显示用户参数、MVC模式和GenParam
Sword finger offer 20 String representing numeric value
Integer array merge [JS]
Pytest learning notes (13) -allure of allure Description () and @allure title()
vulnhub靶场-Hacker_Kid-v1.0.1
随机推荐
Openlayers customize bubble boxes and navigate to bubble boxes
C語言輸入/輸出流和文件操作
中国氮化硅陶瓷基板行业研究与投资前景报告(2022版)
判断一棵二叉树是否为平衡二叉树
China BMS battery management system Market Research Report (2022 Edition)
Concatenate strings to get the result with the smallest dictionary order
换掉UUID,NanoID更快更安全!
6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单
【PyG】文档总结以及项目经验(持续更新
Petrv2: a unified framework for 3D perception of multi camera images
Reflective XSS vulnerability
ACM MM 2022视频理解挑战赛视频分类赛道冠军AutoX团队技术分享
智能运维实战:银行业务流程及单笔交易追踪
Judge whether the binary tree is a binary search tree
PHP implements sensitive word filtering system "suggestions collection"
麦趣尔:媒体报道所涉两批次产品已下架封存,受理消费者诉求
Redis6.0 新功能
在MeterSphere接口测试中如何使用JMeter函数和MockJS函数
【牛客网刷题系列 之 Verilog快速入门】~ 优先编码器电路①
中国酶制剂市场预测与投资战略研究报告(2022版)