当前位置:网站首页>【HBZ分享】Semaphore 与 CountDownLatch原理
【HBZ分享】Semaphore 与 CountDownLatch原理
2022-06-29 10:29:00 【hbz-】
原理:
二者都是基于AQS实现的
Semaphore信号量原理功能介绍
- 利用Semaphore信号量可以做接口等限流,即配置最大信号量后。
- 每调用一次acquire()方法,信号量就会-1, 当减到0时,在调用的acquire的线程就会进入阻塞状态
- 每调用一次release()方法,信号量就会+1, 此时会唤醒阻塞队列中的线程进行执行,并使得信号量-1,直到阻塞队列为空
Semaphore信号量的API及用法
// 创建信号量对象,并赋予最大信号量有5个
Semaphore semaphore = new Semaphore(5);
for(int i =0; i < 10; i++){
// 获取信号量,并把剩余信号两个数 - 1
semaphore.acquire();
System.out.println("执行逻辑");
// 归还信号量
semaphore.release();
}
CountDownLatch原理功能介绍
- 阻塞当前线程
- CountDownLatch countDownLatch = new CountDownLatch(2); 就表示每执行一次countDownLatch.await(),则需要再执行两次countDownLatch.countDown();才能继续执行当前线程
CountDownLatch的API及用法
CountDownLatch countDownLatch = new CountDownLatch(2);
new Thread(()->{
System.out.println("线程开始");
// 把该线程阻塞住
countDownLatch.await();
System.out.println("线程结束");
}).start();
// 执行第一次,并不能释放锁,因为 new CountDownLatch(2);参数时2,此时不会打印【线程结束】
countDownLatct.countDown();
// 执行第二次,才能彻底释放,并接着进行,打印【线程结束】
countDownLatct.countDown();
边栏推荐
- (JS)手写bind函数
- 什么?漫画居然能免费看全本了,这还不学起来一起做省钱小能手
- Bs-gx-018 student examination system based on SSM
- 多线程高并发服务器:3个问题
- NUC980开源项目16-从SPI FLASH(W25Q128)启动
- matlab基础 max 求一维或二维数组的最大值+sleep(pause)
- The last 48 hours! The cloud XR theme competition invites you to bloom together. See you at the competition!
- Spark - Task 与 Partition 一一对应与参数详解
- 第12周实验---基于FPGA的VGA协议实现
- The first "cyborg" in the world died, and he only transformed himself to "change his life against the sky"
猜你喜欢

Bs-gx-017 online examination management system based on SSM

When a technician becomes a CEO, what "bugs" should be modified?

Multi thread communication between client and server (primary version)

ruoyi框架中添加sharding sphere5.0.0分表(通过spi添加自定义分表策略)

直击产业落地!飞桨重磅推出业界首个模型选型工具
![[daily 3 questions (3)] reformat the phone number](/img/ba/0cfe8c084e626615934065b4dee453.png)
[daily 3 questions (3)] reformat the phone number

如何识别出轮廓准确的长和宽

(JS) filter out keys with value greater than 2 in the object

又拍云 Redis 的改进之路

math_ Mathematical expression & deformation of equation equation & accumulation of combined operation skills / means
随机推荐
ruoyi框架中添加sharding sphere5.0.0分表(通过spi添加自定义分表策略)
Lizuofan, co-founder of nonconvex: Taking quantification as his lifelong career
西门子S7-200SMART控制步进电机的具体方法及示例程序
Uber前安全主管面临欺诈指控 曾隐瞒数据泄露事件
[digital signal modulation] realize signal modulation and demodulation based on am+fm+dsb+ssb, including Matlab source code
在日本的 IT 公司工作是怎样一番体验?
(JS)捕获错误(异常)
Several types of MySQL index invalidation and their solutions
(JS)观察者模式
(JS) observer mode
Creating postgre enterprise database by ArcGIS
斐波那锲数列与冒泡排序法在C语言中的用法
【每日3题(2)】生成交替二进制字符串的最少操作数
MATLAB basic Max to find the maximum value of one-dimensional or two-dimensional array +sleep (pause)
BS-GX-017基于SSM实现的在线考试管理系统
云原生开发必备:首个通用无代码开发平台 iVX 编辑器
ModbusTCP协议WIFI无线学习型单路红外模块(小壳版)
(JS)手写深比较
专访 SUSS NiFT 负责人:Web3 的未来离不开“人人为我,我为人人”的治理
Modbus RTU protocol 485 learning 2-way infrared module