当前位置:网站首页>常用的辅助类—(重点)
常用的辅助类—(重点)
2022-06-22 06:10:00 【酷小亚】
并发中必要掌握的三个常用辅助类:
1、CountDownLatch
2、CyclicBarrier
3、Semaphore
1、CountDownLatch
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nZhpugRD-1654964658930)(C:\Users\38492\AppData\Local\Temp\1654961495489.png)]](/img/50/6e50d8875cf3b4235434d632dceafd.png)
倒数计时器
package add;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//倒计时 : 总数是6
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Go out");
countDownLatch.countDown(); // 数量-1
},String.valueOf(i)).start();
}
countDownLatch.await(); //等待计数器归零,然后再向下执行
System.out.println("Close Door");
}
}
原理:
countDownLatch.countDown(); //数量 -1
countDownLatch.await(); //等待计数器归零,然后再向下执行
每次有线程调用 countDown() 数量 -1 ,假设计数器变为0,countDownLatch.await() 就会被唤醒,继续执行!
2、CyclicBarrier
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fki6i2Tw-1654964658944)(C:\Users\38492\AppData\Local\Temp\1654962868165.png)]](/img/4e/fb268b73f2658551259160b45895ed.png)
加法计数器
package add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
/** * 集齐7颗龙珠召唤神龙 */
//召唤龙珠的线程
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙!");
});
for (int i = 1; i <= 7; i++) {
// Lambda 能操作到 i 吗 不能
//想要拿到 i ,用一个final 中间变量就可以了
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");
try {
cyclicBarrier.await(); //等待
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
3、Semaphore
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6afBpciP-1654964658945)(C:\Users\38492\AppData\Local\Temp\1654963594521.png)]](/img/05/d3244324d9111812fc1fa3cc4166cd.png)
停车位! 限流!
6车 ---->3个停车位
package add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
//线程数量: 停车位! 限流!
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6; i++) {
new Thread(()->{
//acquire() 获得
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//release() 释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
原理:
semaphore.acquire(); 获得 , 假设如果满了,等待,等待被释放为止!
semaphore.release(); 释放,会将当前的信号量释放 -1 , 然后唤醒等待的线程!
作用:
多个共享资源互斥的使用!并发限流,控制最大的线程数!
边栏推荐
- Discrete PID control based on MATLAB
- Single cell paper records (Part8) -- cell2location maps fine grained cell types in spatial transcriptomics
- swagger常用注解汇总
- 虚职、架空、拖后腿,大厂开源办公室到底什么样?
- Single cell paper record (Part14) -- costa: unsupervised revolutionary neural network learning for St analysis
- 402-字符串(题目:剑指Offer58-II.左旋转字符串、 28. 实现 strStr()、459.重复的子字符串)
- e. Hash & oldcap = = 0 detailed interpretation
- Flink核心功能和原理
- 【Rust笔记】01-基本类型
- simulink中搭建专家pid控制
猜你喜欢

Ethernet communication protocol

SSM整合所需配置文件及常见配置错误引起的报错

生信可视化(part3)--小提琴图

Research on automatic landing control system of carrier aircraft
![tab[i = (n - 1) & hash] 的详细解读](/img/be/3e84b3e8406833c2a235494f1a035f.png)
tab[i = (n - 1) & hash] 的详细解读

Configuration files required for SSM integration and error reports caused by common configuration errors

Shengxin visualization (Part3) -- violin diagram

Case analysis of terminal data leakage prevention

单细胞论文记录(part9)--Spatial charting of single-cell transcriptomes in tissues

【技术随记】
随机推荐
单细胞论文记录(part10)--Computational challenges and opportunities in SRT data
[Key review of cloud computing]
h = key. Hashcode()) ^ (H > > 16) detailed explanation and why the hashcode value should be shifted to the right by 16 bits and XOR with the original hashcode value
402-字符串(题目:剑指Offer58-II.左旋转字符串、 28. 实现 strStr()、459.重复的子字符串)
单细胞论文记录(part13)--SpaGCN: Integrating gene expression, spatial location and histology to ...
W800 chip platform enters openharmony backbone
PIR控制器调节器并网逆变器电流谐波抑制策略
401 string (344. reverse string, 541. reverse string II, Title: Sword finger offer 05. replace spaces, 151. reverse words in string)
Ethernet communication protocol
单细胞文献学习(part2)--stPlus: a reference-based method for the accurate enhancement of ST
单细胞论文记录(part9)--Spatial charting of single-cell transcriptomes in tissues
【技术随记】
W800芯片平台进入OpenHarmony主干
osg编译osgQt
On the matrix order of MNIST linear model
Unity development - scene asynchronous loading
On the definition of jinja2 macro
What about computer jam?
StopWatch的使用
Bat common batch script record