1.await通常配合while循环使用,防止调用java.util.concurrent.locks.ReentrantLock#lockInterruptibly()方法的情况下发生虚假唤醒的问题
2.ReentrantLock中await和signal必须和相对应的锁配合使用,必须在对应锁的加锁解锁代码中间使用
示例:
private ReentrantLock tailLock = new ReentrantLock();
private Condition headWaits = tailLock.newCondition();
private ReentrantLock headLock = new ReentrantLock();
private Condition tailWaits = headLock.newCondition();
tailLock.lockInterruptibly();
try {
long t = TimeUnit.MILLISECONDS.toNanos(timeout);
while (isFull()) {
if (t <= 0) {
return false;
}
t = tailWaits.awaitNanos(t);
}
array[tail] = e;
if (++tail == array.length) {
tail = 0;
}
// size++;
size.getAndIncrement();
headLock.lock();
try {
headWaits.signal(); // signal()和await()必须配对使用
} finally {
headLock.unlock();
}
return true;
} finally {
tailLock.unlock();
}