我有一段代码(简化):
if(reentrantLockObject.isLocked()) {
reentrantLockObject.unlock();
}
其中 reentrantLockObject 是 java.util.concurrent.locks.ReentrantLock。 有时我会得到 IllegalMonitorStateException。 它接缝在 check 和 unlock() 调用之间释放了锁。 我怎样才能防止这个异常(exception)?
最佳答案
isLocked
返回是否任何 线程持有锁。我想你想要 isHeldByCurrentThread
:
if (reentrantLockObject.isHeldByCurrentThread()) {
reentrantLockObject.unlock();
}
话虽如此,isHeldByCurrentThread
被记录为主要用于诊断目的 - 这段代码是不寻常的正确方法。你能解释一下为什么你认为你需要它吗?
关于java - 在没有 IllegalMonitorStateException 的情况下解锁 ReentrantLock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2811236/