概念
Suspension 是“挂起”、“暂停”的意思,而 Guarded 则是“担保”的意思,连在一起 就是确保挂起。当线程在访问某个对象时,发现条件不满足,就暂时挂起等待条件满足时 再次访问。
Guarded Suspension 设计模式是很多设计模式的基础,比如生产者消费者模式,同 样在 Java 并发包中的 BlockingQueue 中也大量使用到了 Guarded Suspension 设计模 式。
public class GuardedSuspensionQueue {
//定义存放 Integer 类型的QUEUE
private final LinkedList<Integer> QUEUE = new LinkedList<>();
//定义QUEUE的最大容量
private final int LMITI;
public GuardedSuspensionQueue(int LMITI) {
this.LMITI = LMITI;
}
//往队列当中插入 Queue ,如果queue当中的元素超过最大容量,进入阻塞
public synchronized void offer(Integer data) throws InterruptedException {
//判断有没有超过最大容量
if(QUEUE.size() >= LMITI){
System.out.println("-----------队列已满------------");
this.wait();
}
notify();//唤醒take中阻塞的队列
QUEUE.addLast(data);
System.out.println("插入成功,插入的元素为:" + data);
}
//从队列中拿出数据 如果队列为空 表示数据已经拿完
public synchronized Integer take() throws InterruptedException {
if (QUEUE.isEmpty()){
System.out.println("----------队列已空--------------");
this.wait();
}
notify(); //唤醒offer中阻塞的线程继续工作
return QUEUE.removeFirst();
}
}
在 GuardedSuspensionQueue 中,我们需要保证线程安全的是 queue,分别在 take和offer方法中对应的临界值是 queue为空和 queue的数量>=100,当 queue中的数据已 经满时,如果有线程调用 offer 方法则会被挂起( Suspension),同样,当 queue 没有数 据的时候,调用 take 方法也会被挂起。Guarded Suspension 模式是一个非常基础的设计模式,它主要关注的是当某个条件 (临界值)不满足时将操作的线程正确地挂起,以防止出现数据不一致或者操作超过临界值 的控制范围。