The wait/notify of the exercises

Source: Internet
Author: User

Programme one:

 Public classPRINTABC { Public Static voidMain (string[] args) {Atomicinteger synobj=NewAtomicinteger (0); Runnable R=NewThreadModel (synobj); NewThread (R,"A"). Start (); NewThread (R,"B"). Start (); NewThread (R,"C"). Start (); }} Public classThreadModel implements Runnable { Public volatileAtomicinteger ATO;  PublicThreadModel (Atomicinteger ato) { This. ATO =ATO;}  Public voidrun () { for(intI=0;i<Ten; i++) {synchronized (ATO) {if(ATO.Get()%3==0) {System. out. println ("A);Ato.Set(ATO.Get()+1);      Ato.notifyall (); } Else if(ATO.Get()%3==1) {System. out. println ("B);Ato.Set(ATO.Get()+1);      Ato.notifyall (); } Else if(ATO.Get()%3==2) {System. out. println ("C);Ato.Set(ATO.Get()+1);      Ato.notifyall (); } Else{ato.wait (); }    }  } }}

Scenario Two:

 Public classPRINTABC { Public Static voidmain (String [] args) {Atomicinteger ato=NewAtomicinteger (0); ThreadModel Modela=NewThreadModel (ATO,"A",0); ThreadModel Modelb=NewThreadModel (ATO,"B",0); ThreadModel MODELC=NewThreadModel (ATO,"C",0); NewThread (Modela). Start (); NewThread (Modelb). Start (); NewThread (MODELC). Start ();} } Public classThreadModel {PrivateAtomicinteger ATO; PrivateString Printchar; Private intFlag; Private intCount =0;  PublicThreadModel (Atomicinteger ato,string Printchar,intflag) {     This. ATO =ATO;  This. Printchar =Printchar;  This. Flag =Flag; }   Public voidRun () {synchronized (ATO) { while(true) {          if(ATO.Get()%3==flag) {System. out. println (Printchar); ATO.Set(ATO.Get()+1);             Ato.notifyall (); Count++; if(count==Ten) {                 Break; }          }Else{ato.wait (); }       }    } } }

The wait/notify of the exercises

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.