我正在做并发问题的家庭作业。我有很多线程在做特定的事情,还有一个方法决定这些线程什么时候可以访问资源。
所以我的班级看起来像这样:
public class Boss extends ReentrantLock implements Runnable {
Lock access = new ReentrantLock();
Condition canTakeOff = access.newCondition();
Condition canLand = access.newCondition();
public void accessToLanding(){
access.lock();
try{
if(getWaitQueueLength(canTakeOff) > 0){
canTakeOff.notifyAll();
} else if {
/* some other cases */
}
} catch (InterruptedException e){
e.printStackTrace();
} finally {
access.unlock();
}
}
public void run(){
accessToLanding();
}
/* Methods which are called by objects of a different class,
they are awaiting for the signal from accessToLanding.*/
}
我收到了错误:
Exception in thread "Thread-0" java.lang.IllegalArgumentException: Not owner
at java.util.concurrent.locks.AbstractQueuedSynchronizer.getWaitQueueLength(AbstractQueuedSynchronizer.java:1789)
at java.util.concurrent.locks.ReentrantLock.getWaitQueueLength(ReentrantLock.java:720)
我已经检查了文档并且它说当“给定条件与此锁无关”时getWaitQueueLength抛出IllegalArgumentException但是根据我的理解,它与我的代码相关联。 有人能帮助我吗?
答案 0 :(得分:2)
当您调用
时getWaitQueueLength(canTakeOff)
你正在打电话
this.getWaitQueueLength(canTakeOff)
其中此是您的Boss实例。尽管 canTakeOff 已声明有成员,但它不属于属于Boss,它是从 access 获得的条件
我认为您必须稍微改变上述行并使用
access.getWaitQueueLength(canTakeOff)
更多信息:Javadoc getWaitQueueLength throws IllegalArgumentException