当前位置:网站首页>Countdownlatch, cyclicbarrier, semaphore of concurrent programming
Countdownlatch, cyclicbarrier, semaphore of concurrent programming
2022-07-22 04:01:00 【Enlightenment of the mortal world】
CountDownLatch
CountDownLatch This class is in the java.util.concurrent And under the contract
The function of this class is to make a thread wait until other threads have finished executing before executing this thread 、
CountDownLatch It can also be seen from the name , It is actually a counter , The number is the number of threads that need to wait for execution to complete , The number of threads that have not finished executing decreases 1, When the quantity is zero , It means that all threads that need to wait have been executed , Then the waiting thread can continue to execute !
It's a little convoluted , It's not complicated at all :
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(5);
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 5; i++){
service.execute(() -> {
System.out.println(" Start execution " + Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" completion of enforcement " + Thread.currentThread().getName());
latch.countDown();
});
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" All threads have been executed , It's time to ");
}
initialization CountDownLatch by 5, Definition implemented 5 Threads , Each thread waits 3 Seconds later latch.countDown(); Express -1, When 5 After all threads are executed , By latch.await(); The blocked thread begins to execute ,
give the result as follows :
Start execution pool-1-thread-1
Start execution pool-1-thread-2
Start execution pool-1-thread-3
Start execution pool-1-thread-4
Start execution pool-1-thread-5
completion of enforcement pool-1-thread-2
completion of enforcement pool-1-thread-3
completion of enforcement pool-1-thread-1
completion of enforcement pool-1-thread-4
completion of enforcement pool-1-thread-5
All threads have been executed , It's time to
CountDownLatch There is also an overloaded await() Method :await(long timeout, TimeUnit unit) Indicates the timeout time , If you wait for the specified time , It doesn't wait until other threads have finished executing
CyclicBarrier
CyclicBarrier This class is also in java.util.concurrent And under the contract
CyclicBarrier The function of is to wait until all threads reach the specified state at the same time and execute at the same time , such as :
CyclicBarrier barrier = new CyclicBarrier(5);
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 5; i++){
service.submit(()->{
System.out.println(Thread.currentThread().getName() + " Being implemented ....");
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " It's done , Wait for other threads to finish executing ");
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
}catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " Follow up tasks begin ");
});
}
}
give the result as follows :
pool-1-thread-2 Being implemented ....
pool-1-thread-1 Being implemented ....
pool-1-thread-3 Being implemented ....
pool-1-thread-5 Being implemented ....
pool-1-thread-4 Being implemented ....
pool-1-thread-5 It's done , Wait for other threads to finish executing
pool-1-thread-2 It's done , Wait for other threads to finish executing
pool-1-thread-1 It's done , Wait for other threads to finish executing
pool-1-thread-3 It's done , Wait for other threads to finish executing
pool-1-thread-4 It's done , Wait for other threads to finish executing
pool-1-thread-3 Follow up tasks begin
pool-1-thread-2 Follow up tasks begin
pool-1-thread-4 Follow up tasks begin
pool-1-thread-5 Follow up tasks begin
pool-1-thread-1 Follow up tasks begin
CyclicBarrier There are two constructors :
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
public CyclicBarrier(int parties) {
this(parties, null);
}
parties It means how many threads need to wait until they reach the specified state to execute
Runnable barrierAction The second parameter indicates that when the threads have reached the specified state , Execute first barrierAction, Then execute at the same time . That is, they have reached the specified state , Then do some additional operations , such as :
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
@Override
public void run() {
System.out.println(" Some other operations are needed !");
}
});
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 5; i++){
service.submit(()->{
System.out.println(Thread.currentThread().getName() + " Being implemented ....");
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " It's done , Wait for other threads to finish executing ");
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
}catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " Follow up tasks begin ");
});
}
}
give the result as follows :
pool-1-thread-1 Being implemented ....
pool-1-thread-2 Being implemented ....
pool-1-thread-3 Being implemented ....
pool-1-thread-4 Being implemented ....
pool-1-thread-5 Being implemented ....
pool-1-thread-3 It's done , Wait for other threads to finish executing
pool-1-thread-4 It's done , Wait for other threads to finish executing
pool-1-thread-2 It's done , Wait for other threads to finish executing
pool-1-thread-1 It's done , Wait for other threads to finish executing
pool-1-thread-5 It's done , Wait for other threads to finish executing
Some other operations are needed !
pool-1-thread-5 Follow up tasks begin
pool-1-thread-3 Follow up tasks begin
pool-1-thread-4 Follow up tasks begin
pool-1-thread-1 Follow up tasks begin
pool-1-thread-2 Follow up tasks begin
barrier.await(); There is another overloaded method :
public int await(long timeout, TimeUnit unit)
and CountDownLatch similar , Define a timeout mechanism , It means that if it's time, you don't have to wait until all threads reach a certain state , We'll start .
It's important to note that CyclicBarrier , It's reusable , Otherwise, how can there be Cyclic Well . After a round of thread execution , You can continue to call awiat, Carry out a new round of waiting operations , however CountDownLatch Can not be !
CountDownLatch and CyclicBarrier Different emphasis ,CountDownLatch The emphasis is that some tasks have been completed , And then the following operations . and CyclicBarrier It means that when all threads wait for each other to a certain state, they carry out subsequent operations at the same time !
Semaphore
Semaphore It literally means semaphore , It indicates how many threads start executing at the same time :
ExecutorService pool = Executors.newFixedThreadPool(10);
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 5; i++){
pool.submit(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " Get the execution right of the thread ");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " completion of enforcement ");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
result :
pool-1-thread-1 Get the execution right of the thread
pool-1-thread-2 Get the execution right of the thread
pool-1-thread-3 Get the execution right of the thread
pool-1-thread-1 completion of enforcement
pool-1-thread-3 completion of enforcement
pool-1-thread-2 completion of enforcement
pool-1-thread-4 Get the execution right of the thread
pool-1-thread-5 Get the execution right of the thread
pool-1-thread-5 completion of enforcement
pool-1-thread-4 completion of enforcement
because semaphore Initialization is specified as 3, It means that only three threads can execute at the same time , So we have to wait until the thread finishes executing the call release Method , The first 4 The first 5 Threads can execute .
No small progress , multiply 356 The sky will also become great !
Welcome to my official account. : A snail walking alone in the north wind
边栏推荐
猜你喜欢
3.1栈
xxl-job源码阅读笔记
[CCF CSP] 201903-1 small, medium and large
10 papers of ant security laboratory were included by ccf-a top meeting to explore the realization of AI credibility from the perspective of algorithm
2.3线性表的链式表示(2)
Baidu world 2022, see you tomorrow!
PAM4科普
50 places are limited to open | with the news of oceanbase's annual press conference coming!
Web
Field injection is not recommended
随机推荐
2.3线性表的链式表示(1)
MySQL 优化系列(2)-- InnoDB重要参数优化
密码学知识-加密介绍-1
How to build a good knowledge base management system?
3.2 queue
Application of SCA on devsecops platform
【CCF CSP】201712-1最小差值
2.3 chain representation of linear table (1)
【CCF CSP】201809-1卖菜
xxl-job源码阅读笔记
Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration
Converter
The pit trodden by real people tells you to avoid the 10 mistakes that novices in automated testing often make
严蔚敏第二章课后习题(2.29-2.38)
10 papers of ant security laboratory were included by ccf-a top meeting to explore the realization of AI credibility from the perspective of algorithm
【CCF CSP】201403-1相反数
3.1 stack
[CCF CSP] 201803-1 jump jump
3.1栈
SATA协议OOB随笔