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

前端之家收集整理的这篇文章主要介绍了java – 条件 – 应该在等待之前解锁?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
你能不能告诉我是否应该在等待条件之前释放锁?
try {
    lock.lock();
    while (isNotEmpty()) {
        condition.await();
    }
} finally {
    lock.unlock();
}

要么

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

解决方法

不,您不需要显式释放锁,等待将自动释放.从 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相关文章