当前位置:网站首页>Multithreading 06 -- countdownlatch, cyclicbarrier, semaphore
Multithreading 06 -- countdownlatch, cyclicbarrier, semaphore
2022-07-22 20:54:00 【fengxianaa】
Last one : Multithreading 05--ReentrantLock principle _fengxianaa The blog of -CSDN Blog
1. CountDownLatch
/**
* CountDownLatch
* Allow a thread to wait for other threads to complete before executing , Often used at work
*/
public class Lock04 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for(int i=0;i<5;i++){
new Thread(() ->{
try{
String name = Thread.currentThread().getName();
if("Thread-0".equals(name)){
System.out.println(name+" sit back ...");
Thread.sleep(3000);
}
System.out.println(name+" Have finished eating ...");
}catch (Exception e){
e.printStackTrace();
}finally {
// It's best to put this code in finally in , Prevent failure to countDown
countDownLatch.countDown();
}
}).start();
}
countDownLatch.await();
System.out.println(" Have finished eating ...");
}
}
2. CyclicBarrier
/**
* CyclicBarrier
* Circulation barrier , Let a group of threads reach a barrier ( It can also be called synchronization point ) When is blocked , Until the last thread reaches the barrier , The barrier will open , All threads blocked by the barrier will continue to run
*
* CyclicBarrier(int parties)
* parties: Indicates the number of threads that need to be intercepted
*
* await()
* If the current thread is not the last thread , Then calling this method will be blocked . Unless one of the following scenarios occurs :
* The last thread arrived
* A thread interrupts the current thread or Another waiting thread
* A thread is waiting barrier Time out
* A thread is here barrier On the call reset()
*
* If the current thread , It has been interrupted when entering this method or Interrupted while waiting , throw :InterruptedException
* If the thread is interrupt , Then other waiting threads will throw BrokenBarrierException abnormal , And will barrier Set to damaged state
*/
public class Lock05 {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
Thread t0 = new Thread(() -> {
try {
String name = Thread.currentThread().getName();
System.out.println(name + " here we are ...");
cyclicBarrier.await();
System.out.println(name + " Start eating ...");
} catch (Exception e) {
e.printStackTrace();
}
});
t0.start();
Thread.sleep(2000);
Thread t1 = new Thread(() -> {
try {
String name = Thread.currentThread().getName();
System.out.println(name + " here we are ...");
cyclicBarrier.await();
System.out.println(name + " Start eating ...");
} catch (Exception e) {
e.printStackTrace();
}
});
t1.start();
// Thread.sleep(1000);
// t0.interrupt();
}
3. Semaphore
/**
* Semaphore
* Semaphore , Control the number of threads accessing specific resources at the same time
*
* Semaphore(int permits)
* Accept an integer number , Indicates the number of licenses available
*
* acquire()
* Block the current thread , Until you get a license , Blocking time , If you are interrupt, throw :InterruptedException
*
* void release()
* * Release a license , Don't forget it. finally Use in , Be careful : Call the method many times , Will increase the number of semaphores allowed , Achieve the effect of dynamic expansion , Such as : initial permits by 1, Called twice release, The maximum license will change to 2
*
* void acquire(int permits)
* Get the specified number of licenses , If there is no available license, it will be blocked and waiting
*
* boolean tryAcquire()
* Try to get a permission from the semaphore , If no license is available , Go straight back to false, It won't block
*
* boolean tryAcquire(int permits)
* Try to get the specified number of licenses , If no license is available, return directly to false
*
* boolean tryAcquire(int permits, long timeout, TimeUnit unit)
* Try to get permission from semaphore within a specified time , If it is successful within the specified time , return true, Otherwise return to false
*
* int availablePermits()
* Get permission for the current semaphore available
*/
public class Lock06 {
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
Semaphore semaphore = new Semaphore(2);
for(int i=0;i<3;i++){
new Thread(() -> {
try {
semaphore.acquire();// Get a license
String name = Thread.currentThread().getName();
System.out.println(name + " Began to run ...");
} catch (Exception e) {
e.printStackTrace();
}finally {
semaphore.release();// Release license
}
}).start();
}
}
}
边栏推荐
猜你喜欢
Charles 抓包原理与实践
基于非线性最坏情况分析的电荷缩放 DAC 中电容器的新棋盘放置和尺寸调整方法
Redis 系列14--Redis Cluster
JMeter performance test
DEFORMABLE DETR 论文精度,并解析网络模型结构
Simulated student information input interface
Automatic current mirror layout (acml) tool
考虑器件匹配和寄生最小化的共质心电容器布局生成
Performance perception of transistor arrays in analog circuits common centroid layout and wiring align
信号耦合约束下扭曲共质心电容器阵列的布线能力
随机推荐
Binary search (recursive function)
信号耦合约束下扭曲共质心电容器阵列的布线能力
安装pycharm
数据分析的步骤和常用方法
Steps and common methods of data analysis
项目上线,旧数据需要修改,写SQL太麻烦,看Excel配合简单SQL的强大功能
spark常用的算子
Common centroid layout of active and passive equipment: review and future road
面向高性能计算场景的存储系统解决方案
Servlet
Leetcode high frequency question: what is the difference between the combat effectiveness of the two soldiers with the closest combat effectiveness of N soldiers in the challenge arena
线程池02--源码
自动电流镜布局 (ACML) 工具
1045 favorite color stripe (30 points)
ASP.NET Core部署手册:4.注意事项和问题排查
1053 path of equal weight (30 points)
【FPGA】:ip核---乘法器(multiplier)
具有非矩形布局1结构的电流镜的梯度灵敏度降低
New attribute of class (elementary understanding)
动态内存和静态内存浅析