void Notify () wakes a single thread waiting on this object monitor
void Notifyall () wakes up all the threads waiting on this object monitor
void Wait () causes the current thread to wait until other threads call the Notify () method of this object or the Notifyall () method
The key points to remember about waiting/notifications are:
The Wait (), notify (), Notifyall () methods must be called from within the synchronization environment. A thread cannot invoke a method of waiting or notifying on an object unless it has a lock on that object.
Wait (), notify (), Notifyall () are instance methods of object. As with each object has a lock, each object can have a list of threads that they wait for from that signal (notification). The thread obtains this waiting list by executing the Wait () method on the object. From that point on, it no longer executes any other instructions until the Notify () method of the object is called. If multiple threads are waiting on the same object, only one thread (not guaranteed in what order) will be selected to continue execution. If no threads are waiting, no special action is taken
Public classThreada { Public Static voidMain (string[] args) {threadb b=Newthreadb (); //Start COMPUTE threadB.start (); //thread A has a lock on the B object. The thread must be the owner of that object lock in order to call the Wait () or Notify () method synchronized(b) {Try{System.out.println ("Wait for object B to complete the calculation ... "); //current thread A waitsb.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (The sum of the B object calculations is: "+b.total); } }} Public classThreadbextendsThread {intTotal ; Public voidrun () {synchronized( This) { for(inti = 0; I < 101; i++) { Total+=i; } //(completed) wakes a single thread waiting on this object monitor, and in this case, the middle thread A is awakenednotify (); } }}
In most cases, it is best to notify all threads waiting for an object. If you do this, you can use Notifyall () on the object to have all threads waiting on this object rush out of the waiting area and return to the operational state
Java-based threading interaction