【问题标题】:Understanding giving up Lock within wait()理解在 wait() 中放弃锁
【发布时间】:2019-02-11 08:46:45
【问题描述】:

来自 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】:

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

“与此 Condition 关联的锁被原子释放,当前线程被禁用以用于线程调度目的并处于休眠状态,直到发生四种情况之一......”

【讨论】:

    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 2018-03-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 2011-11-15
    相关资源
    最近更新 更多