当前位置:网站首页>Countdownlatch and join [concurrent programming]
Countdownlatch and join [concurrent programming]
2022-07-24 09:39:00 【liuyunshengsir】
Business scenario description : Suppose there are three workers on an assembly line :worker1,worker2,worker3. There is a task to be completed by the three of them ,worker3 The premise of starting this task is worker1 and worker2 Finished their work , and worker1 and worker2 They can work in parallel .
1.join Realization
public class CountDownLatchAndJoin {
public static void main(String[] args) throws InterruptedException {
// Three independent worker threads
worker worker1 = new worker("worker1", (long) (Math.random()*4000));
worker worker2 = new worker("worker2", (long) (Math.random()*4000));
worker worker3 = new worker("worker3", (long) (Math.random()*4000));
// worker worker1 = new worker("worker1", 6000);
// worker worker2 = new worker("worker2", 5000);
// worker worker3 = new worker("worker3", 5000);
worker1.start();
worker2.start();
worker1.join();
worker2.join();
System.out.println(" Ready for work ...");
worker3.start();
}
// Workers
public static class worker extends Thread {
// name
private String name;
// working hours
private long time;
worker(String name, long time) {
this.name = name;
this.time = time;
}
public void run() {
try {
System.out.println(name + " start-up ");
Thread.sleep(time);
System.out.println(name + " completion of jobs , Time consuming =" + time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
result :
worker2 start-up
worker1 start-up
worker1 completion of jobs , Time consuming =601
worker2 completion of jobs , Time consuming =2886
Ready for work …
worker3 start-up
worker3 completion of jobs , Time consuming =686
Can complete the work smoothly ,join It works by , Keep checking thread Survival , If alive, let the current thread forever wait, until thread Thread termination , Thread notifyAll It will be called , It can also be understood as join It means cutting in line
2.CountDownLatch Realization
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
// The initialization counter is 2
CountDownLatch countDownLatch = new CountDownLatch(2);
// Three independent worker threads
worker worker1 = new worker("worker1", (long) (Math.random() * 4000), countDownLatch);
worker worker2 = new worker("worker2", (long) (Math.random() * 4000), countDownLatch);
worker worker3 = new worker("worker3", (long) (Math.random() * 4000), countDownLatch);
worker1.start();
worker2.start();
// When the counter is not 0 Waiting all the time
countDownLatch.await();
System.out.println(" Ready for work ...");
worker3.start();
}
public static class worker extends Thread {
private String name;
private long time;
private CountDownLatch countDownLatch;
worker(String name, long time, CountDownLatch countDownLatch) {
this.name = name;
this.time = time;
this.countDownLatch = countDownLatch;
}
public void run() {
System.out.println(name + " It 's working ...");
// Minus one
countDownLatch.countDown();
System.out.println(name + " completion of jobs ...");
}
}
}
Create a counter for 2 Of CountDownLatch , Give Way Worker Hold this CountDownLatch example , When you finish your work , call countDownLatch.countDown() Method to decrement the counter 1.countDownLatch.await() Method will block until the counter is 0, The main thread will continue to execute .
Running results :
worker1 It 's working ...
worker1 completion of jobs ...
worker2 It 's working ...
worker2 completion of jobs ...
Ready for work …
worker3 It 's working ...
worker3 completion of jobs ...
In terms of results , All solved the problem , But what is the difference between them ?
Business scenario : hypothesis worker Our work can be divided into two stages ,work3 Just wait work1 and work2 After completing the first stage of their respective work, they can start their own work , Not the scene 1 You must wait work1 and work2 Don't start until they have finished all their work . such join It can't be achieved , We should use CountDownLatch To achieve .
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
// The initialization counter is 5
CountDownLatch countDownLatch = new CountDownLatch(5);
// Three independent worker threads
worker worker1 = new worker("worker1", (long) (Math.random() * 4000), countDownLatch);
worker worker2 = new worker("worker2", (long) (Math.random() * 4000), countDownLatch);
worker worker3 = new worker("worker3", (long) (Math.random() * 4000), countDownLatch);
worker worker4 = new worker("worker4", (long) (Math.random() * 4000), countDownLatch);
worker worker5 = new worker("worker5", (long) (Math.random() * 4000), countDownLatch);
worker worker6 = new worker("worker6", (long) (Math.random() * 4000), countDownLatch);
worker1.start();
worker2.start();
worker3.start();
worker4.start();
worker5.start();
// When the counter is not 0 Waiting all the time
countDownLatch.await();
System.out.println(" Ready for work ...");
worker6.start();
}
public static class worker extends Thread {
private String name;
private long time;
private CountDownLatch countDownLatch;
worker(String name, long time, CountDownLatch countDownLatch) {
this.name = name;
this.time = time;
this.countDownLatch = countDownLatch;
}
public void run() {
try {
System.out.println(name + " Work begins ...");
Thread.sleep(time);
System.out.println(name + " The first stage is finished ... when :" + time);
// Counter minus one
countDownLatch.countDown();
// Suppose that the work of the second stage takes two seconds to complete
Thread.sleep(2000);
System.out.println(name + " The second stage is completed ... when :" + (time + 2000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Run more times and find : Threads 6 Wait until the front 5 The first stage of threads is completed , It's running , Running results :
worker3 Work begins ...
worker2 Work begins ...
worker1 Work begins ...
worker4 Work begins ...
worker5 Work begins ...
worker3 The first stage is finished ... when :1410
worker5 The first stage is finished ... when :2022
worker2 The first stage is finished ... when :2273
worker1 The first stage is finished ... when :2856
worker3 The second stage is completed ... when :3410
worker4 The first stage is finished ... when :3430
Ready for work …
worker6 Work begins ...
worker5 The second stage is completed ... when :4022
worker2 The second stage is completed ... when :4273
worker1 The second stage is completed ... when :4856
worker4 The second stage is completed ... when :5430
worker6 The first stage is finished ... when :3773
worker6 The second stage is completed ... when :5773
summary : call thread.join() Method must wait thread completion of enforcement , The current thread can continue to execute , and CountDownLatch More flexible control is provided through counters , As long as it is detected that the counter is 0 The current thread can execute down without taking care of the corresponding thread Whether the implementation is completed .
边栏推荐
- Linux deployment mysql8.0
- Code random notes_ Linked list_ Turn over the linked list in groups of 25K
- SQL 优化原则
- Onpropertychange property
- Scheme and software analysis of dual computer hot standby system "suggestions collection"
- [200 opencv routines] 236. Principal component analysis of feature extraction (openCV)
- The difference between & &, | and |
- [the first anniversary of my creation] love needs to be commemorated, so does creation
- [assembly language practice] (II). Write a program to calculate the value of expression w=v- (x+y+z-51) (including code and process screenshots)
- Embedded development: Tools - optimizing firmware using DRT
猜你喜欢

来阿里一年后我迎来了第一次工作变动....

Friends come to interview a unicorn company in Beijing at leisure. The interview question is priced at 25K

Detailed sequence traversal of leetcode102 binary tree
![[the first anniversary of my creation] love needs to be commemorated, so does creation](/img/89/2f8eec4f0a0bcf77d5a91179012899.png)
[the first anniversary of my creation] love needs to be commemorated, so does creation

Spark Learning: using RDD API to implement inverted index
![[don't bother to strengthen learning] video notes (III) 2. SARS learning realizes maze walking](/img/a8/0d3bd3cc2b3e1d43e201e5dfe4b729.png)
[don't bother to strengthen learning] video notes (III) 2. SARS learning realizes maze walking

js定位大全获取节点的兄弟,父级,子级元素含robot实例

Scarcity in Web3: how to become a winner in a decentralized world

web安全入门-开源防火墙Pfsense安装配置

DP longest common subsequence detailed version (LCS)
随机推荐
[Luogu p5829] [template] mismatch tree (string) (KMP)
It's eleven again. Those jokes about nagging programmers going home for blind dates
Es search summary
唐宇迪opencv-背景建模
Scala learning: why emphasize immutable objects?
Vector control of permanent magnet synchronous motor (I) -- mathematical model
Detailed sequence traversal of leetcode102 binary tree
Android system security - 5.2-apk V1 signature introduction
Tang Yudi opencv background modeling
Getting started with web security - open source firewall pfsense installation configuration
DSP development, using CCS software to establish engineering and burning
Promise基础总结
华为无线设备安全策略配置命令
Cloud primordial (12) | introduction to kubernetes foundation of kubernetes chapter
代码随想录笔记_链表_25K个一组翻转链表
Will your NFT disappear? Dfinity provides the best solution for NFT storage
Racecar multi-point navigation experiment based on ROS communication mechanism
PHP Basics - PHP magic method
Foreign lead operation takes one month to collect money, and the sideline still needs it
Boundless dialogue | participate in the live broadcast on July 25 and win the prize