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();
}