0

wait() と notify() または notifyAll() を呼び出すたびに、 illegalMoniterStateException が発生します。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() と言って、そのロックを保持しているスレッドを 1 つ解放します。

....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 に答える