This article goes on, and then we introduce the wait () and notify () methods, and we all know that the two methods are not the same as the methods described earlier, that is, the two methods are object objects, not on the thread class . We also know that these two methods are implemented between multiple threads of communication and mutual exclusion , not much to say, the following look at the example:
Example Description:
Two threads are turned on, the child thread loops 10 times, the main thread loops 100 times, so the loop is repeated 50 times
The code is as follows:
Public Static voidMain (string[] args) {FinalBusiness Business =NewBusiness (); //Child Threads Loop 10 times NewThread (NewRunnable () {@Override Public voidrun () { for(inti=0;i<50;i++) {business.sub (i); }}). Start (); //main thread Loop 100 times for(inti=0;i<50;i++) {business.main (i); } } /*** Business Logic class *@authorweijiang204321 **/ Static classbusiness{PrivateVolatileBooleanBshouldsub =true;//True indicates that the sub executes, false indicates that main executes Public synchronized voidSubinti) { //change the If to while, the effect is better, while will again judge, High security//because sometimes threads can be woken up by false while(!bshouldsub) { Try { //wait This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } for(intj=0;j<=10;j++) {System.out.println ("Sub thread Sequece of" + j + ", loop of" +i); } bshouldsub=false; This. Notify ();//The waiting thread that wakes the lock } Public synchronized voidMaininti) { while(bshouldsub) {Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } for(intj=0;j<=100;j++) {System.out.println ("Main thread Sequece of" + j + ", loop of" +i); } bshouldsub=true; This. Notify (); } } }
through the wait and notify mechanism to achieve the two threads of the order of the loop, to ensure that the child thread loop 10 times, the main thread loop 100 times so alternately run .
Run a lot of results, here is not! Here we can also see that the call to wait method is to release the lock , so he will be used a lot, this and the previous several methods are different!
Two points to note:
First: Synchronizing the locks in the code block and calling the object lock of the wait and Notifiy methods must be the same.
Second: Wait and notify method calls must be in the synchronization code block, or will report an exception, you can test it yourself.
go to: http://blog.csdn.net/jiangwei0910410003/article/details/19962565
Objects in Java object method---Wait () and notifiy ()