After the thread security is resolved, the following problems still exist:
A: If the consumer first grab the CPU execution right, will go to consume data, but now the data is the default value, no meaning, should wait for the data to have meaning, and then consumption.
B: If the producer first grabbed the CPU's execution, it would go to production data, but, after it produced the data, it continued to have executive power, and it continued to produce data. This is problematic, and it should wait for consumers to consume the data and then produce it.
The normal idea:
A: Producers: first see whether there is data, there is waiting, there is no production, after the production to inform consumers to consume data.
B: Consumers: First whether there is data, there is consumption, no wait, notify producers of production data.
To deal with such problems, Java provides a mechanism to wait for a wake-up mechanism.
Waiting to wake up: There are three methods available in the Object class:
Wait (): Wait
Notify (): Wake up a single thread
Notifyall (): Wake All Threads
Why are these methods not defined in the thread class?
The invocation of these methods must be called by the lock object, and all lock objects can be called, and the method should be on their common parent class, the object class.
Example: Inter-thread communication: Producer consumer (Waiting for wake-up mechanism)
Packagecom.test; Public classStudent {String name; intAge ; BooleanisTrue; Public synchronized voidSet (String name,intAge ) { /**If you have data, wait for it.*/ if( This. IsTrue) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } /**Setting up data*/ This. Name =name; This. Age =Age ; /**Modify Tags*/ This. IsTrue =true; This. Notify (); } Public synchronized voidget () {/**If there is no data, wait*/ if(! This. IsTrue) { Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } /**Get Data*/System.out.println ( This. Name + "---" + This. Age); /**Modify Tags*/ This. IsTrue =false; This. Notify (); }}
Packagecom.test; Public classSetthreadImplementsRunnable {PrivateStudent S; Private intx = 0; PublicSetthread (Student s) { This. S =s; } @Override Public voidrun () { while(true) { if(x% 2 = = 0) {S.set ("Leaf Fat", 27); } Else{S.set ("Wang Skinny", 31); } x++; } }}
Package com.test; Public class Implements Runnable { private Student s; Public GetThread (Student s) { this. s= s; } @Override publicvoid run () { while (true ) { s.get (); }}}
Packagecom.test; Public classStudenttest { Public Static voidMain (string[] args) {Student s=NewStudent (); Setthread St=NewSetthread (s); GetThread GT=NewGetThread (s); Thread T1=NewThread (ST); Thread T2=NewThread (GT); T1.start (); T2.start (); }}
"Inter-thread communication: Waiting for Wake-up mechanism"