Two threads operate the same resource, such as input and output, and operate on the same object, at which time two lines routines for the execution of the CPU , switching randomly. We want to achieve the first input and then output, sequential execution
The target object defines a tag field to be judged, and theWait () and notify () methods
Wait () method, the thread is in a waiting state, and the waiting thread is in the in-memory thread pool
Notify () method to wake the thread in the thread pool
Notifyall () method to wake up all threads
The above method, which needs to be written in the synchronization, and need to identify the lock
These methods of manipulating threads are defined in object objects, because these methods are called by the same lock object
/*** Resources * *@authorTaoshihan **/classpeople {String name; String sex; Boolean MyLock=false;}/*** Input * *@authorTaoshihan **/classPeoplejoinImplementsRunnable {Privatepeople resource; PublicPeoplejoin (People Resource) { This. Resource =resource; } @Override Public voidrun () {//Toggle BooleanFlag =true; while(true) { synchronized(Resource) {if(resource.mylock) {Try{resource.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } if(flag) {Resource.name= "Taoshihan"; Resource.sex= "Nan"; } Else{resource.name= "Taoshan"; Resource.sex= "Male"; } Flag= !Flag; Resource.mylock=true; Resource.notify (); } } }}/*** Output * *@authorTaoshihan **/classPeopleoutImplementsRunnable {Privatepeople resource; PublicPeopleout (People Resource) { This. Resource =resource; } @Override Public voidrun () { while(true) { synchronized(Resource) {if(!Resource.mylock) { Try{resource.wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println (Resource.name+ "=====" +resource.sex); Resource.mylock=false; Resource.notify (); } } }} Public classThreaddemo {/** * @paramargs*/ Public Static voidMain (string[] args) {people resource=Newpeople (); Peoplejoin input=NewPeoplejoin (Resource); Peopleout Output=NewPeopleout (Resource); Thread T1=NewThread (input); Thread T2=NewThread (output); T1.start (); T2.start (); }}
[Javase] multithreaded communication (wait-wake mechanism)