理解在wait()内放弃锁定

问题描述 投票:1回答:1

来自Java Condition Docs

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条件是真的所以ProducenotFull.await()。我的问题是现在,如果一个线程Consume调用take,在说lock.lock()究竟发生了什么?

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

java multithreading concurrency operating-system
1个回答
1
投票

如果你仔细观察Condition.await()的Javadoc,你会看到await()方法以原子方式释放锁并暂停自身:

“与此条件相关联的锁被原子释放,并且当前线程因线程调度而被禁用,并处于休眠状态,直到发生四件事之一......”

© www.soinside.com 2019 - 2024. All rights reserved.