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 分钟前
StringBuilder类的数据结构和扩容方式解读
java
索迪迈科技1 小时前
java后端工程师进修ing(研一版 || day40)
java·开发语言·学习·算法
十碗饭吃不饱1 小时前
net::ERR_EMPTY_RESPONSE
java·javascript·chrome·html5
白初&1 小时前
SpringBoot后端基础案例
java·spring boot·后端
哈基米喜欢哈哈哈1 小时前
ThreadLocal 内存泄露风险解析
java·jvm·面试
萌新小码农‍1 小时前
Java分页 Element—UI
java·开发语言·ui
鼠鼠我捏,要死了捏1 小时前
深入实践G1垃圾收集器调优:Java应用性能优化实战指南
java·g1·gc调优
书院门前细致的苹果2 小时前
ArrayList、LinkedList、Vector 的区别与底层实现
java
再睡亿分钟!2 小时前
Spring MVC 的常用注解
java·开发语言·spring boot·spring
至此流年莫相忘2 小时前
设计模式:策略模式
设计模式·策略模式