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();
}
}
}
相关推荐
geovindu25 分钟前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
会编程的吕洞宾6 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤6 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha6 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
RobinXYuan7 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!7 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
SimonKing8 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
CoderYanger8 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
Rain的Java大神之路8 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
蜡笔小谢18 小时前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness