can solve the following problem, basically can understand the thread mutex and synchronization.
The child thread loops 10 times, the main thread loops 100 times, then the child thread loops 10, and the main thread loops 100 times. So the reciprocating cycle 50 times.
1 PackageCn.lah.thread;2 3 Public classtraditionalthreadcommunication {4 5 Public Static voidMain (string[] args) {6 7 FinalBusiness Business =NewBusiness ();8 NewThread (NewRunnable () {9 Public voidrun () {Ten for(inti = 1; I <= 50; i++) { One business.sub (i); A } - } - }). Start (); the - for(inti = 1; I <= 50; i++) { - Business.main (i); - } + - } + A } at - //defines a business logic class that is attributed to this class of thread synchronization related methods, which can achieve high cohesion and enhance the robustness of code - classBusiness { - - Private BooleanBeshouldsub =true; - in Public synchronized voidSubinti) { - while(!beshouldsub) { to Try { + This. Wait (); -}Catch(interruptedexception e) { the e.printstacktrace (); * } $ }Panax Notoginseng for(intj = 1; J <= 10; J + +) { -System.out.println ("Sub Thread" + j + "loop" +i); the } +Beshouldsub =false; A This. Notify (); the } + - Public synchronized voidMaininti) { $ while(beshouldsub) { $ Try { - This. Wait (); -}Catch(interruptedexception e) { the e.printstacktrace (); - }Wuyi } the for(intj = 1; J <= 100; J + +) { -System.out.println ("main Thread" + j + "loop" +i); Wu } -Beshouldsub =true; About This. Notify (); $ } -}
Thread Mutex and synchronization