当前位置:网站首页>Introduction to the use of countdownlatch and cyclicbarrier for inter thread control
Introduction to the use of countdownlatch and cyclicbarrier for inter thread control
2022-04-23 14:15:00 【pureluckyfish】
One 、CountDownLatch Introduce
CountDownLatch class ( Count by subtraction ); Is a thread synchronization helper class and CyclicBarrier class ( Counting by addition ) The function is similar to , Allow one or more threads to wait , Until a set of operations performed in other threads is complete .
Two 、CountDownLatch Two application scenarios :
Scene one : All threads are waiting for the start signal startSignal.await(), The main flow sends a start signal to inform , Both implementation startSignal.countDown() After the method , All threads begin to execute ; Each thread sends a completion signal after execution , Both implementation doneSignal.countDown() Method ; When all threads are executed , The main process can continue to execute .
package ThreadStudy;
import java.util.concurrent.CountDownLatch;
public class Driver1 {
public static void main(String[] args) throws InterruptedException {
int N = 5;
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(N);
for (int i = 0; i < N; i++) {
new Thread(new Work1(startSignal, doneSignal)).start();
}
// At this point, all threads are in a waiting state
System.out.println("doSomethingElse()");
// Let all threads execute
startSignal.countDown();
// Wait for all threads to finish executing
doneSignal.await();
System.out.println("doSomethingElse()");
}
}
class Work1 implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
public Work1(CountDownLatch startSignal,CountDownLatch doneSignal) {
this.startSignal=startSignal;
this.doneSignal= doneSignal;
}
@Override
public void run() {
try {
startSignal.await();
doWork();
doneSignal.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void doWork() {
System.out.println("doWork()");
}
}
Scene two : Divide a big problem into N Parts of , Each part corresponds to a thread, which is put into the thread pool to execute , When the execution of each thread is completed, a completion signal is sent , Both call doneSignal.countDown() Method ; When all threads are executed , The main process can continue to execute .
package ThreadStudy;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Driver2 {
public static void main(String[] args) throws Exception {
int N = 5;
CountDownLatch doneSignal = new CountDownLatch(N);
// Define thread pool
ExecutorService exec = Executors.newSingleThreadExecutor();
for (int i = 0; i < N; i++) {
exec.execute(new Work2(doneSignal, i));
}
// Wait for all threads to complete
doneSignal.await();
System.out.println("doSomethingElse()");
// Close thread pool
exec.shutdown();
}
}
class Work2 implements Runnable {
private CountDownLatch doneSignal;
private int i;
public Work2(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
@Override
public void run() {
doWork(i);
doneSignal.countDown();
}
void doWork(int i) {
System.out.println("doWork():" + i);
}
}
3、 ... and 、CountDownLatch And CyclicBarrier contrast
| CountDownLatch | CyclicBarrier | |
| The same thing | Are synchronization helper classes | |
| Difference | Subtraction counting , One time use | Add count , It can be recycled |
| Construction method | CountDownLatch(int count) |
CyclicBarrier(int parties) |
| CyclicBarrier(int parties, Runnable barrierAction) | ||
| Common method | await() | await() |
| await(long timeout, TimeUnit unit) | await(long timeout, TimeUnit unit) | |
| countDown() | getNumberWaiting() | |
| getCount() | getParties() | |
| toString() | isBroken() | |
| reset() | ||
Four 、CountDownLatch Class
package ThreadStudy;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Csdn {
public static void main(String[] args) throws Exception {
int countLatch = 3;
// Create a specified number of latches
CountDownLatch countDownLatch = new CountDownLatch(countLatch);
System.out.println("toString Method 0:" + countDownLatch.toString());
for (int i = 0; i < countLatch; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// Reduce the number of latches by one
Thread.sleep(3000);
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// Get the number of latches
long n = countDownLatch.getCount();
System.out.println(" Number of latches :" + n);
// Specify the timeout for waiting
countDownLatch.await(1, TimeUnit.SECONDS);
System.out.println(" After the timeout, the program continues to execute ");
// The current thread is waiting , Until the number of latches is 0, The program goes down
countDownLatch.await();
System.out.println("toString Method 1:" + countDownLatch.toString());
}
}
5、 ... and 、CyclicBarrier Class
package ThreadStudy;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class CyclicBarrierTest {
public static void main(String[] args) {
// Construction method 1 : Create a thread for 3 Circulation barrier of ,3 After all threads reach the obstacle point , Just go down !
CyclicBarrier cb1 = new CyclicBarrier(3);
// Construction method 2 : Create a new CyclicBarrier, When the last thread passes through the obstacle point, it will trigger the thread execution here
CyclicBarrier cb = new CyclicBarrier(3, new Runnable() {
@Override
public void run() {
System.out.println("== The thread that triggers execution after passing the obstacle point ==");
}
});
// Returns the number of people currently waiting at the barrier . This method is mainly used for debugging and asserting
int a = cb.getNumberWaiting();
System.out.println(" Returns the number of people currently waiting at the barrier " + a);
// Return the number of people needed to cross the barrier
int b = cb.getParties();
System.out.println(" Return the number of people needed to cross the barrier :" + b);
// Check whether the barrier is in an interrupted state :
boolean bo = cb.isBroken();
System.out.println(" Check whether the barrier is in an interrupted state :" + bo);
for (int i = 0; i < 4; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Threads :" + Thread.currentThread().getName() + " Enter the obstacle point and wait ");
try {
// wait for , Until all parties have invoked... On this barrier await.
int d = cb.await();
System.out.println("d:" + d);
// wait for , Until all parties have invoked... On this barrier await, Or the specified waiting time has passed
int c = cb.await(1, TimeUnit.SECONDS);
System.out.println("c:" + c);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(" Through obstacles ");
}
}).start();
}
// Reset operation , At this point, the thread waiting at the obstacle point will throw BrokenBarrierException abnormal
cb.reset();
}
}
版权声明
本文为[pureluckyfish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231406486003.html
边栏推荐
- Can I compile the header file and source file of the template separately
- 文字组合,不重复,做搜索或查询关键字匹配
- redis数据库讲解(四)主从复制、哨兵、Cluster群集
- OpenStack命令操作
- 统信UOS卸载php7.2.24,安装php7.4.27 ;卸载再安装为PHP 7.2.34
- 教育行业云迁移最佳实践:海云捷迅使用HyperMotion云迁移产品为北京某大学实施渐进式迁移,成功率100%
- Some experience of using dialogfragment and anti stepping pit experience (getactivity and getdialog are empty, cancelable is invalid, etc.)
- On the multi-level certificate based on OpenSSL, the issuance and management of multi-level Ca, and two-way authentication
- MySQL-InnoDB-事务
- rsync+inotify远程同步
猜你喜欢

Operation instructions of star boundary automatic text translator (advanced version)

处理 mkdir:无法创建目录“aaa“:只读文件系统

OpenStack如何跨版本升级

On the multi-level certificate based on OpenSSL, the issuance and management of multi-level Ca, and two-way authentication

ThreadGroup ThreadGroup implémente l'interface threadfactory en utilisant la classe Introduction + Custom thread Factory

Win10 comes with groove music, which can't play cue and ape files. It's a curvilinear way to save the country. It creates its own aimpack plug-in package, and aimp installs DSP plug-in

HyperBDR云容灾V3.3.0版本发布|容灾功能升级,资源组管理功能优化

Research on recyclerview details - Discussion and repair of recyclerview click dislocation

统信UOS PHP7.2.3升级至PHP7.2.24

星界边境文本自动翻译机使用说明
随机推荐
MySQL数据库讲解(十)
MySQL基础知识
Request module
HyperBDR云容灾V3.3.0版本发布|容灾功能升级,资源组管理功能优化
使用开源调研工具Prophet是一种什么体验?
如何轻松做好一个项目
js 递归(1)
Can global variables be defined in header files
连接公司跳板机取别名
Idea控制台乱码解决
Jmeter设置环境变量支持在任意终端目录输入jmeter直接启动
mysql 5.1升级到5.610
ActiveMq基础知识
redis数据库讲解二(redis高可用、持久化、性能管理)
Quickly understand the three ways of thread implementation
Logging module
线程组ThreadGroup使用介绍+自定义线程工厂类实现ThreadFactory接口
xx项目架构随记
krpano全景之vtour文件夹和tour
帆软中使用if else 进行判断-使用标题条件进行判断