Guarded Suspension(担保挂起)设计模式

当线程访问某个对象时,发现条件不满足,暂时挂起等待条件满足时再次访问。Guarded Suspension模式是一个非常基础的模式,主要关注(临界值)不满足时将操作的线程正确挂起,以防止出现数据不一致或者操作超过临界值的控制范围。它是很多线程设计模式的基础。

示例代码:

java 复制代码
import java.util.LinkedList;

public class GuardedSuspensionQueue {
private final LinkedList<Integer> queue=new LinkedList<>();
private final int LIMIT=100;

public void offer(Integer data) throws InterruptedException{
synchronized(this) {
while(queue.size()>=LIMIT) {
this.wait();
}
queue.addLast(data);
this.notifyAll();
}
}

public Integer take() throws InterruptedException{
synchronized(this) {
while(queue.isEmpty()) {
this.wait();
}
this.notifyAll();
return queue.removeFirst();
}
}
}
相关推荐
workflower2 小时前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
YuanlongWang2 小时前
C# 基础——装箱和拆箱
java·开发语言·c#
b78gb2 小时前
电商秒杀系统设计 Java+MySQL实现高并发库存管理与订单处理
java·开发语言·mysql
wb043072014 小时前
性能优化实战:基于方法执行监控与AI调用链分析
java·人工智能·spring boot·语言模型·性能优化
天若有情6735 小时前
Java Swing 实战:从零打造经典黄金矿工游戏
java·后端·游戏·黄金矿工·swin
lichong9515 小时前
Android studio 修改包名
android·java·前端·ide·android studio·大前端·大前端++
lichong9515 小时前
Git 检出到HEAD 再修改提交commit 会消失解决方案
java·前端·git·python·github·大前端·大前端++
@yanyu6665 小时前
Tomcat安装与HTML响应实战
java·tomcat·html
Chen-Edward7 小时前
有了Spring为什么还有要Spring Boot?
java·spring boot·spring
陈小桔7 小时前
idea中重新加载所有maven项目失败,但maven compile成功
java·maven