通常、待機/通知は、他のスレッドがタスクを完了するのを待機するか、特定の条件が満たされるまで待機するために使用されます。
objectAというオブジェクトと、thread1 および thread2という 2 つのスレッドがあるとします。
thread1にはスレッドセーフなタスクがあるため、同期ブロック を使用して objectA のモニターを取得します。
synchronized (objectA) {
//here thread1 owns objectA's monitor
}
Java では、wait() を呼び出すことは、他のスレッドがこのモニターを取得してそのタスクを実行できるようにモニターを解放することを意味し、現在のスレッドはobjectA のモニターの待機状態と呼ばれる状態になります。
synchronized(objectA){
//here thread1 owns objectA's monitor.
objectA.wait();
//here thred1 releases monitor of objectA's monitor and goes into waiting state and waits to get objectA's monitor once again to complete its task.
}
これで、thread2 は objectA のモニターを所有し、そのタスクを実行できます。
synchronized(objectA){
//here thread2 owns objectA's monitor.
//some task;
}
タスクが完了すると、待機状態にある他のスレッドに、所有するオブジェクトのモニターが解放されたことを通知します。notify()を呼び出すには、スレッドもオブジェクト monitor の所有者である必要があることに注意してください。
synchronized(objectA){
//here thread2 owns objectA's monitor.
//some task;
objectA.notify();
//it signals some other thread that it can wake up from wait,so that other waiting threads can owns objectA's monitor
}
ここで、 objectAで wait() を呼び出し、他のオブジェクト (objectB としましょう) で notify() を呼び出しても、thread1 は使用されません。
1 つのオブジェクトで notify() を呼び出そうとする 2 つのスレッドが互いに足を踏み入れないことが保証されているため (競合状態を回避するため)、notify()Why obtain monitor to call notify()
を
呼び出すように更新します。通知する前にロックを取得する必要がある理由