gpt4 book ai didi

java - 了解在 wait() 中放弃锁

转载 作者:行者123 更新时间:2023-11-30 06:01:32 26 4
gpt4 key购买 nike

来自 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 条件为 true,因此 Produce 会执行 notFull.await()。我现在的问题是,如果线程 Consume 调用 take,在 lock.lock() 行上到底会发生什么?

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

最佳答案

如果您仔细查看 Javadoc Condition.await() ,您将看到await()方法自动释放锁并挂起自身:

“与此条件关联的锁被自动释放,当前线程出于线程调度目的而被禁用,并处于 hibernate 状态,直到发生以下四种情况之一......”

关于java - 了解在 wait() 中放弃锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52198117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com