Thread Mutex and synchronization

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.