Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作。此实现允许更灵活的结构,可以具有差别很大的属性,可以支持多个相关的 Condition 对象。
  public class Storage<T> {
  // 仓库大存储量
  private final int MAX_SIZE = 1000;
  private int storageSize = 100;
  private Object[] data;
  private int top = 0;
  private Lock lock = new ReentrantLock();
  private Condition producerCon = lock.newCondition();
  private Condition consumerCon = lock.newCondition();
  public Storage(int size) {
  size = size <= 0 ? storageSize : size;
  size = size > this.MAX_SIZE ? this.MAX_SIZE : size;
  this.storageSize = size;
  data = new Object[this.storageSize];
  }
  public int getStorageSize() {
  return storageSize;
  }
  public T pop() throws InterruptedException {
  T t = null;
  lock.lock();
  try {
  while (top == 0) {
  //消费者等待
  consumerCon.await();
  }
  top--;
  t = (T) data[top];
  //唤醒生产者
  producerCon.signal();
  } finally {
  lock.unlock();
  }
  return t;
  }
  public void push(T t) throws InterruptedException {
  lock.lock();
  try {
  while (top == storageSize) {
  //生产者等待
  producerCon.await();
  }
  data[top++] = t;
  //唤醒消费者
  consumerCon.signal();
  } finally {
  lock.unlock();
  }
  }
  }