Guarded Suspension 设计模式

x33g5p2x  于2022-04-22 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(258)

一 点睛

当线程在访问某个对象时,发现条件不满足,就暂时挂起等待条件满足时再次访问,这就是 Guarded Suspension 设计模式。该设计模式的关注点在于临界值的条件是否满足,当达到设置的临界值时相关线程则会挂起。

二 代码

package concurrent;

import java.util.LinkedList;

public class GuardSuspensionQueue {
    // 定义存放 Integer 类型的 queue
    private final LinkedList<Integer> queue = new LinkedList<>();
    // 定义 queue 的最大容量
    private final int LIMIT = 100;

    // 在 queue 中插入数据,如果 queue 中的元素超过了最大容量,则会陷入阻塞
    public void offer(Integer data) throws InterruptedException {
        synchronized (this) {
            // 判断 queue 的当前元素是否超过了 LIMIT
            while (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();
        }
    }
}

三 说明

在 GuardSuspensionQueue 中,需要保证线程安全的是 queue,分别在 take 和 offer 方法中对应的临界值是 queue 为空和 queue 的数量 >= 100,当 queue 中的数据已经满时,如果有线程调用 offer 方法则会被挂起(Suspension),同样,当 queue 没有数据的时候,调用 take 方法也会被挂起。

相关文章

微信公众号

最新文章

更多