内置条件队列
通知
状态依赖方法的标准形式
void stateDependentMethod() throws InterruptedException {
synchronized (lock) {
while (!conditionPredicate())
locak.wait();
// 现在对象处于合适的状态
}
}示例
最后更新于
void stateDependentMethod() throws InterruptedException {
synchronized (lock) {
while (!conditionPredicate())
locak.wait();
// 现在对象处于合适的状态
}
}最后更新于
public final class BoundedBuffer<T> {
private final T[] buffer;
private int head, tail, count;
public BoundedBuffer(int capacity) {
this.buffer = (T[]) new Object[capacity];
}
public void put(T e) throws InterruptedException {
synchronized (this) {
while (isFull())
wait();
boolean isEmpty = isEmpty();
doPut(e);
if (isEmpty) // 条件通知(优化措施)
notifyAll();
}
}
public T take() throws InterruptedException {
synchronized (this) {
while (isEmpty())
wait();
boolean isFull = isFull();
T result = doTake();
if (isFull) // 条件通知(优化措施)
notifyAll();
return result;
}
}
private void doPut(T e) {
buffer[tail] = e;
if (++tail == buffer.length)
tail = 0;
count++;
}
private T doTake() {
T result = buffer[head];
buffer[head] = null; // 避免内存泄露
if (++head == buffer.length)
head = 0;
count--;
return result;
}
private boolean isFull() {
return this.count == buffer.length;
}
private boolean isEmpty() {
return this.count == 0;
}
}