Condition 實現原理
說 Codition 前,需要說下 ConditioObject。
ConditionObject 是同步器 AbstractQueuedSynchronzied 的內部類,因爲 Condition 的操作需要關聯的鎖。 ArrayBlockingQueue 就是 Condition 的具體應用。 Object 中其實 也有 wait ,notify ,notifyAll 等操作, Condition 相當於將 wait ,notify ,notifyAll 轉換成想要的對象,將比較難懂的同步操作變成直觀可控的對象行爲。
應用場景 ArrayBlockingQueue
ArrayBlockingQueue 的構造函數。
/** Main lock guarding all access */
final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
通過構造函數,可以看到 Condition 的創建時需要關聯鎖的。
從隊列中去取出(take)數據 。