当前位置:网站首页>CyclicBarrier回环栅栏
CyclicBarrier回环栅栏
2022-08-05 19:20:00 【季风泯灭的季节】

// parties表示屏障拦截的线程数量,每个线程调用 await 方法告诉 CyclicBarrier 我已经到达了屏障,然后当前线程被阻塞。
public CyclicBarrier(int parties)
// 用于在线程到达屏障时,优先执行 barrierAction,方便处理更复杂的业务场景(该线程的执行时机是在有parties个线程到达屏障之后再执行)
public CyclicBarrier(int parties, Runnable barrierAction) //屏障 指定数量的线程全部调用await()方法时,这些线程不再阻塞
// BrokenBarrierException 表示栅栏已经被破坏,破坏的原因可能是其中一个线程 await() 时被中断或者超时
public int await() throws InterruptedException, BrokenBarrierException
public int await(long timeout, TimeUnit unit) throws InterruptedException, Bro kenBarrierException, TimeoutException
//循环 通过reset()方法可以进行重置
public void reset() //保存每个学生的平均成绩
private ConcurrentHashMap<String, Integer> map=new ConcurrentHashMap<String,Integer>();
private ExecutorService threadPool= Executors.newFixedThreadPool(3);
// 3个线程到达栅栏后执行相加计算
private CyclicBarrier cb=new CyclicBarrier(3,()->{
int result=0;
Set<String> set = map.keySet();
for(String s:set){
result+=map.get(s);
}
System.out.println("三人平均成绩为:"+(result/3)+"分");
});
public void count(){
for(int i=0;i<3;i++){
threadPool.execute(new Runnable(){
@Override
public void run() {
//获取学生平均成绩
int score=(int)(Math.random()*40+60);
map.put(Thread.currentThread().getName(), score);
System.out.println(Thread.currentThread().getName()
+"同学的平均成绩为:"+score);
try {
//执行完运行await(),等待所有学生平均成绩都计算完毕
cb.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
});
}
}
public static void main(String[] args) {
CyclicBarrierTest2 cb=new CyclicBarrierTest2();
cb.count();
}边栏推荐
猜你喜欢

rhcsa 第一次作业
![[Illustrated and textual] Detailed explanation of the method of one-click reinstallation of the Win11 system](/img/d4/8b64cec37e38e23bac60d646b8d909.png)
[Illustrated and textual] Detailed explanation of the method of one-click reinstallation of the Win11 system

【图文并茂】一键重装Win11系统方法详解

encodeURI、encodeURIComponent decodeURI decodeURIComponent

MVC设计思想

IDEA运行参数配置

Biotin-HPDP(129179-83-5),一个巯基反应性的生物素化试剂

Mysql insert and update processing field is the key database

MySQL8016 expire_logs_days参数不生效

【机器学习】50个最佳机器学习公共数据集
随机推荐
php session 的使用
The MVC design ideas
Basic application of JSP
卸载Node
最新接口有关抖音,获取抖音分享口令url API
LeetCode_逆向思维_中等_453.最小操作次数使数组元素相等
【无标题】
Josn应用
Basic application of Js
【 Jmeter聚合报告 】
一建证书有什么用?拿到一级建造师证书能干什么?
华为研究院19级研究员几年心得终成趣谈网络协议文档,附大牛讲解
Good code in the eyes of compiler engineers (1): Loop Interchange
给根目录扩容
RHCE 作业一
一文看懂推荐系统:召回08:双塔模型——线上服务需要离线存物品向量、模型更新分为全量更新和增量更新
Kettle需求场景复现
tiup cluster audit
uniapp中用canvas实现小球碰撞的小动画
申请证券账户在手机开通安全吗?