1

来自 Java条件文档

class BoundedBuffer<E> {
   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(E 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 E take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0)
         notEmpty.await();
       E x = (E) items[takeptr];
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   }
 }

假设一个线程Produce调用put,所以Produce现在拥有锁lock。但while条件为真也是Produce如此notFull.await()。我现在的问题是,如果一个线程Consume调用take, 在lock.lock()说明到底发生了什么的那一行?

我有点困惑,因为我们让旧lock的进入关键部分,现在需要从不同的线程获取它。

4

1 回答 1

1

如果您仔细查看Condition.await()的 Javadoc ,您会看到 await() 方法以原子方式释放锁并自行挂起:

“与此条件关联的锁被自动释放,当前线程出于线程调度目的而被禁用并处于休眠状态,直到发生四件事之一……”

于 2018-09-08T01:15:08.850 回答