当我尝试解锁对象时抛出以下异常。
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 是一个可重入锁
你知道问题可能出在哪里吗?
编辑:
这是 Station 中的运行方法
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;
}