概念
guarded是“被保护着的”、“被防卫着的”意思,suspension则是“暂停”的意思。当现在并不适合马上执行某个操作时,就要求想要执行该操作的线程等待,这就是Guarded Suspension Pattern。
Guarded Suspension Pattern 会要求线程等候,以保障实例的安全性,其它类似的称呼还有guarded wait、spin lock等。
Guarded Suspension示例
package com.zl.step20;
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(Integer data) throws InterruptedException{
synchronized (this){
while(queue.isEmpty()){
this.wait();
}
this.notifyAll();
return queue.removeFirst();
}
}
}