Learn about the use of the Wait method and the Notify method in Java multi-threading.
Use of the wait and notify methods a simple instance of wait and notify
ImportJava.util.concurrent.TimeUnit; Public classWaitthreadtest { Public Static voidMain (string[] args)throwsException {Object Object=NewObject (); NewWaitthread (Object). Start (); TimeUnit.SECONDS.sleep (2);//wake up after 2 seconds NewNotifythread (Object). Start (); } Static classWaitthreadextendsThread {PrivateObject object; Waitthread (Object object) { This. Object =object; } @Override Public voidrun () {synchronized(object) {Try{System.out.println ("Before wait."); Object.wait (); System.out.println ("After wait."); } Catch(interruptedexception e) {e.printstacktrace (); } } } } Static classNotifythreadextendsThread {PrivateObject object; Notifythread (Object object) { This. Object =object; } @Override Public voidrun () {synchronized(object) {System.out.println ("Before notify."); Object.notify (); System.out.println ("After notify."); } } }}
The results of the operation are as follows:
Before Wait.before notify.after notify.after wait.
If you modify Object.wait () to object.wait (1), the result of the operation is as follows:
Before Wait.after Wait.before notify.after notify.
Friendship Link
Java Foundation---->java Multi-threaded use (eight)