了解在wait()中放弃Lock

时间:2018-09-06 06:53:44

标签: java multithreading concurrency operating-system

从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条件成立,因此Produce确实notFull.await()。我的问题是,如果一个线程Consume调用take,在显示lock.lock()的那一行上,究竟会发生什么?

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

1 个答案:

答案 0 :(得分:1)

如果您仔细查看Condition.await()的Javadoc,您会发现await()方法以原子方式释放了锁并使其自身挂起:

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