0

每当我调用 wait() 和 notify() 或 notifyAll() 时,我都会收到非法监视器状态异常。javadoc说如果我的线程“试图在对象的监视器上等待或通知其他线程在对象的监视器上等待而不拥有指定的监视器”,我应该得到那个异常。

但是,这是我在上面调用这些方法的代码示例。

//note that doSomething will be called by a thread from another class, not this one
public void doSomething(){
    while(objectsCurrentlyDoingSomething() >= thisClass'sCapacity){
         synchronized(objectLock){ //objectLock is created at top of class like this:
             wait(2000);           //private static final Object objectLock = new Object();
         }
    }

    //rest of code
}

然后稍后我通过说如果对象完成,减少当前使用的对象数量和 notify() 来释放一个持有该锁的线程。

....object finished......
synchronized(objectLock){
    notify();
}
4

2 回答 2

4

您需要调用等待,并在 objectLock 上通知。

例如

objectLock.wait()

它你只是调用wait()你正在调用它this

于 2012-10-31T19:54:38.067 回答
1

正如 z5h 所指出的,您对 wait() 和 notify() 的调用应该在 objectLock 对象上进行:

//note that doSomething will be called by a thread from another class, not this one
public void doSomething(){
    while(objectsCurrentlyDoingSomething() >= thisClass'sCapacity){
         synchronized(objectLock){ //objectLock is created at top of class like this:
             objectLock.wait(2000);           //private static final Object objectLock = new Object();
         }
    }

    //rest of code
}

....object finished......
synchronized(objectLock){
    objectLock.notify();
}
于 2012-10-31T19:55:49.317 回答