在可重入锁中等待条件。

7 浏览
0 Comments

在可重入锁中等待条件。

以下代码摘自Condition的JavaDoc

class BoundedBuffer {
  final Lock lock = new ReentrantLock();
  final Condition notFull  = lock.newCondition(); 
  final Condition notEmpty = lock.newCondition(); 
  final Object[] items = new Object[100];
  int putptr, takeptr, count;
  public void put(Object x) throws InterruptedException {
    lock.lock();
    try {
      while (count == items.length) 
        notFull.await();
      items[putptr] = x; 
      if (++putptr == items.length) putptr = 0;
      ++count;
      notEmpty.signal();
    } finally {
      lock.unlock();
    }
  }
  public Object take() throws InterruptedException {
    lock.lock();
    try {
      while (count == 0) 
        notEmpty.await();
      Object x = items[takeptr]; 
      if (++takeptr == items.length) takeptr = 0;
      --count;
      notFull.signal();
      return x;
    } finally {
      lock.unlock();
    }
  } 
}

假设有两个线程,消费者(Consumer)和生产者(Producer),它们在同一个BoundedBuffer实例上分别使用take和put方法。

假设消费者先执行,调用take()方法,在该方法中获取lock锁并在notEmpty.await()处循环等待。

那么生产者如何能够在获取到lock锁之后进入put()方法,而这个锁已经被消费者持有了呢?

我在这里漏掉了什么?在线程等待条件时,锁是否会被“临时释放”?锁的再进入是什么意思?

0