- Three methods
Wait ()
Notify ()
Notifyall ()
All three methods are used in synchronization because the thread holding the lock (also called monitoring) is being manipulated.
So to use in synchronization, because only synchronization has a lock.
- Why are the methods of these operations threads present in the object class?
Because these methods must be used to identify the operating thread that has a lock in the operation of the thread in synchronization. Only the same locked thread that is waiting can be awakened by the same locked notify, and the threads in different locks cannot be awakened.
In other words, wait and wake must be the same lock.
Public class Demo1 { Public Static voidMain (string[] args) {Res res =NewRes (); Input i =NewInput (RES); Output o =NewOutput (RES); Thread T1 =NewThread (i); Thread t2 =NewThread (o); T1.start (); T2.start (); }} class Res { PrivateString name;PrivateString gender;Private BooleanFlag PublicSynchronizedvoidSetnamegender (string name, string gender) {if(flag)Try{ This. Wait (); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } This. name = name; This. gender = gender; This. Flag =true; This. Notify (); } PublicSynchronizedvoidOut () {if(! This. Flag)Try{ This. Wait (); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println ( This. Name +" : "+ This. gender); This. Flag =false; This. Notify (); }} class Input implements Runnable { PrivateRes res; Input (res res) { This. res = res; } Public voidRun () {intx =0; while(true) {if(x%3==0) {Res.setnamegender ("T-mac","Male"); }Else if(x%3==1) {Res.setnamegender ("McGrady","Man"); }Else{Res.setnamegender ("CBA","Bad"); } x + +; } }} class Output implements Runnable { PrivateRes res; Output (res res) { This. res = res; } Public voidRun () { while(true) {res.out (); } }}
Java multithreading-thread-waiting wakeup mechanism for inter-thread communication