发现条件不满足时,就暂时挂起等待条件满足,常见的在BlockingQueue中含有大量的Guarded Suspension模式
public class GuardedSuspensionQueue<T>{
private final LinkedList<T> queue = new LinkedList<>();
private final int LIMIT;
GardedSuspensionQueue(){
LIMIT = 100;
}
GardedSuspensionQueue(int maxSize){
LIMIT = maxSize
}
public void offer(T data) throws InterruptedException{
synchronized(this){
while(queue.size() >= LIMIT){
this.wait();
}
queue.addLast(data);
this.nofifyAll();
}
}
public void take(){
synchronized(this){
while(queue.isEmpty()){
this.wait();
}
this.notifyAll();
return queue.removeFirst();
}
}
}
上面的代码可以通过This充当锁,也可以通过定义一个Object对象充当锁。