gpt4 book ai didi

java - 为什么我会收到 IllegalMonitorStateException?

转载 作者:行者123 更新时间:2023-12-01 11:24:04 29 4
gpt4 key购买 nike

当我尝试解锁一个对象时,我收到以下异常。

Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(Unknown Source)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(Unknown Source)
at java.util.concurrent.locks.ReentrantLock.unlock(Unknown Source)
at Pipe.unlock(Pipe.java:21)
at Station.doWork(Station.java:81)
at Station.run(Station.java:66)
at java.lang.Thread.run(Unknown Source)

Pipe.unlock 所做的一切如下:
public void unlock(){
accessLock.unlock();
}

其中 accessLock 是 ReentrantLock

你知道问题出在哪里吗?

编辑:

这是Station中的run方法
if(Pipes[inConnection].accessLock.tryLock()){
System.out.println("Station "+ StationNumber+": granted access to pipe "+inConnection+".");

//This is just a way for me to keep track if both pipes have been granted
if(connected<0)
connected=inConnection;
else
connected+=inConnection;
}


if(Pipes[outConnection].accessLock.tryLock()){
System.out.println("Station "+ StationNumber+": granted access to pipe "+outConnection+".");

//This is just a way for me to keep track if both pipes have been granted
if(connected<0)
connected=outConnection;
else
connected+=outConnection;
}


doWork();

虽然这是 doWork 方法:
private void doWork() {
if(connected==inConnection+outConnection){
System.out.println("Station "+StationNumber+": successfully flows "+inConnection+".");
System.out.println("Station "+StationNumber+": successfully flows "+outConnection+".");

Pipes[inConnection].unlock();
System.out.println("Station "+StationNumber+": released access to pipe "+inConnection+".");

Pipes[outConnection].unlock();
System.out.println("Station "+StationNumber+": released access to pipe "+outConnection+".");

try {
Thread.sleep(rand.nextInt(200));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

WorkLoad--;
}else if(connected >=0 ){
Pipes[connected].unlock();
System.out.println("Station "+StationNumber+": released access to pipe "+connected);

}

connected=-1;
}

最佳答案

我知道这个问题已经有一年多了,但我遇到了同样的问题,结果证明解决方案不是另一个以某种方式持有锁的线程,而是一个非常简单的错误和 ReentrantLock 的内部细节。如果我们看一下 tryRelease 的实现:

protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
..
if (c == 0) {
..
setExclusiveOwnerThread(null);
}
..
}

如果发布计数降为零,则exclusiveOwnerThread 设置为空。如果您之后再次尝试释放锁,您就不再是exclusiveOwnerThread,因为您的线程不太可能为空。所以一个简单的 .unlock() 太多会导致这个(在这种情况下相当困惑)异常。

关于java - 为什么我会收到 IllegalMonitorStateException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884061/

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