Notify () and Notifyall () are all methods that object objects use to inform the thread that is waiting on the object
- void Notify (): Wakes up a thread that is waiting for the object.
- void Notifyall (): Wakes all threads that are waiting on the object.
The biggest difference between the two is:
- Notifyall causes all threads that originally wait on the object to be notify to exit the wait state, becoming a lock on the object, and once the object is unlocked, they compete.
- Notify he just chooses a wait-state thread to notify, and it gets the lock on the object, but does not disturb other threads that are also waiting to be notify by the object, releasing the lock on the object when the first thread finishes running, and if the object does not use the Notify statement again, Even if the object is idle, the other waiting-state waits for the thread to remain in the wait state until it emits a notify or notifyall, and waits for a notify or notifyall instead of a lock, because the object is not notified.
When multiple threads have the same synchronization object, an instance with Notifyall will cause an exception
Importjava.util.ArrayList;Importjava.util.List;classwidget{}classWidgetmakerextendsthread{List finishedwidgets=NewArrayList (); Public voidrun () {Try{ while(true){ //every 5s generated object added to listThread.Sleep (5000); Widget W=Newwidgets (); Widget I=Newwidgets (); Widget D=Newwidgets (); synchronized(finishedwidgets) {finishedwidgets.add (w); Finishedwidgets.add (i); Finishedwidgets.add (d); //notifies the wait object to wake after adding 3 elements to the list//if Notifyall () is used here, the first thread gets the lock, and the other thread is awakened from the wait state to execute the Remove command, the partial list appears with an empty element remove exception, and notify only selects the current wait state thread to wake up. And make it get the lock on the object, but not the other threads that are waiting to be notify by the objectfinishedwidgets.notify (); } } }Catch(Interruptedexception e) {}}//If the list is there, it will always return until the list is empty wait PublicWidget Waitforwiget () {synchronized(finishedwidgets) {if(finishedwidgets.size () = = 0) { Try{finishedwidgets.wait (); } Catch(Interruptedexception e) {}}return(Widget) finishedwidgets.remove (0); } }} Public classWidgetuserextendsthread{PrivateWidgetmaker maker; PublicWidgetuser (String name,widgetmaker maker) {Super(name); This. Maker =maker; } Public voidrun () {Widget W=Maker.waitforwiget (); System.out.println (GetName ()+ "Got a widget"); } Public Static voidMain (string[] args) {Widgetmaker maker=NewWidgetmaker (); Maker.start (); NewWidgetuser ("Lenny", maker). Start (); NewWidgetuser ("Moe"), maker). Start (); NewWidgetuser ("Curly", maker). Start (); }}
Differences between Java notify () and Notifyall () synchronous wakeup