gpt4 book ai didi

java - 条件 - 应该在等待之前解锁吗?

转载 作者:搜寻专家 更新时间:2023-10-30 21:15:52 24 4
gpt4 key购买 nike

你能告诉我是否应该在条件等待之前释放锁吗?

try {
lock.lock();
while (isNotEmpty()) {
condition.await();
}
} finally {
lock.unlock();
}

或者

try {
lock.lock();
while (isNotEmpty()) {
lock.unlock();
condition.await();
}
} finally {
lock.unlock();
}

最佳答案

不,你不需要在调用await之前显式释放锁,await会自动释放它。来自 javadoc :

The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes[...]

和:

The current thread is assumed to hold the lock associated with this Condition when this method is called.

关于java - 条件 - 应该在等待之前解锁吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11308768/

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