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();
}
}
}
相关推荐
爱笑的源码基地28 分钟前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
莫逸风3 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
z123456789864 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
yaoxin5211234 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
做个文艺程序员4 小时前
Linux第24篇:Java应用监控体系搭建:Prometheus+Grafana可视化运维
java·grafana·prometheus
小钻风33665 小时前
Spring Boot 文件上传详解:深入理解 MultipartFile 的使用与原理
java·开发语言
其美杰布-富贵-李5 小时前
Spring Boot 工程开发全流程说明
java·spring boot·后端
前端双越老师7 小时前
如何以前端视角(非0基础)学 Java ?
java·node.js·全栈
dear_bi_MyOnly7 小时前
【SpringBoot配置文件】
java·spring boot·后端·学习·spring·java-ee·学习方法
做个文艺程序员7 小时前
Linux第22篇:用Docker容器化你的Java SaaS应用:一次构建,随处运行
java·docker·容器