Java高并发 - 20.Guarded Suspension设计模式

Suspension是“挂起”的意思,而Guarded则是“担保”的意思,连在一起就是确保挂起。当线程在访问某个对象时,发现条件不满足,就暂时挂起等待条件满足时再次访问。这一点与Balking设计模式刚好相反(Balking在遇到条件不满足时会放弃)。

示例

public class GuardedSuspensionQueue {
	// 定义存放Integer类型的queue
	private final LinkedList<Integer> queue = new LinkedList<>();
	// 定义queue的最大容量为100
	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.addList(data);
			this.notifyAll();
		}
	}
	
	// 从queue中获取数据,如果queue此时为空,则会陷入阻塞
	public Integer take() throws InterruptedException {
		synchronized(this) {
			// 判断queue是否为空
			while (queue.isEmpty()) {
				this.wait();
			}
			// 通知offer线程可以继续插入数据了
			this.notifyAll();
			return queue.removeFirst();
		}
	}
}