什么是 Guarded Suspension 设计模式
Guarded Suspension 的示例
public class GuardedSuspensionQueue{//定义存放 Integer 类型的 queueprivate final LinkedList<Integer> queue = new LinkedList<>();//定义 queue 的最大容量为100private final int LIMIT = 100;//往 queue 中插入数据,如果 queue 中的元素超过了最大容量,则会陷入阻塞public void offer(Integer data) throws InterruptedException{synchronized (this){//判断 queue 的当前元素是否超过了 LIMITwhile (queue.size() >= LIMIT){//挂起当前线程,使其陷入阻塞this.wait();}//插入元素并且唤醒 take 线程queue.addLast(data);this.notifyAll();}}//从队列中获取元素,如果队列此时为空,则会使当前线程阻塞public Integer take() throws InterruptedException{synchronized (this){//判断如果队列为空while (queue.isEmpty()){//则挂起当前线程this.wait();}//通知 offer 线程可以继续插入数据了this.notifyAll();return queue.removeFirst();}}}
文章转载自Alleria Windrunner,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




