Java Inter-thread communication

Source: Internet
Author: User

/*inter-thread communication: Multiple threads are working on the same resource, but the tasks are different. */ Packagecom.cwcec.test;classInputImplementsrunnable{Resource R;  PublicInput (Resource r) { This. R =R; }        Public voidrun () {intx = 0;  while(true)           {               synchronized(r) {if(x = = 0) {R.name= "Mike"; R.sex= "Nan"; }                      Else{r.name= "Lili"; R.sex= "female"; } x= (x + 1)% 2; }                          }       }}classOutputImplementsrunnable{Resource R;  PublicOutput (Resource r) { This. R =R; }     Public voidrun () { while(true)        {            synchronized(R) {System.out.println (R.name+ "..." +r.sex); }                    }    }}classresource{String name; String sex;} Public classPerson { Public Static voidMain (string[] args) {Resource R=NewResource (); Input in=NewInput (R); Output Output=NewOutput (R); Thread T1=NewThread (in); Thread T2=NewThread (output);        T1.start ();    T2.start (); }}
Output:Mike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanMike...nanLily ... FemaleLily ... FemaleLily ... FemaleLily ... FemaleLily ... FemaleLily ... FemaleLily ... Female

/* wait/wake mechanism. Method involved: 1,wait (): Threads are frozen and wait threads are stored in the thread pool. 2,notify (): Wakes a thread in the thread pool (any). 3,notifyall (): Wakes all threads in the thread pool. All of these methods must be defined in synchronization. Because these methods are the methods used to manipulate the thread state.  It is important to be clear on which locked thread the operation is.  Why is the method for manipulating threads wait notify Notifyall defined in the object class? Because these methods are the methods of the monitor. A monitor is actually a lock. A lock can be any object, and the way an arbitrary object is called must be defined in the object class.
classInputImplementsrunnable{Resource R;  PublicInput (Resource r) { This. R =R; }        Public voidrun () {intx = 0;  while(true)           {               synchronized(r) {if(r.flag) {Try{r.wait (); } Catch(interruptedexception e) {e.printstacktrace (); }                   }                                      if(x = = 0) {R.name= "Mike"; R.sex= "Nan"; }                      Else{r.name= "Lili"; R.sex= "female"; } R.flag=true;            R.notify (); } x= (x + 1)% 2; }       }}classOutputImplementsrunnable{Resource R;  PublicOutput (Resource r) { This. R =R; }     Public voidrun () { while(true)        {            synchronized(r) {if(!R.flag)Try{r.wait (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (R.name+ "..." +r.sex); R.flag=false;            R.notify (); }        }    }}classresource{String name;   String sex; BooleanFlag =false;} Public classPerson { Public Static voidMain (string[] args) {Resource R=NewResource (); Input in=NewInput (R); Output Output=NewOutput (R); Thread T1=NewThread (in); Thread T2=NewThread (output);        T1.start ();    T2.start (); }}
Output:Mike...nanLily ... FemaleMike...nanLily ... FemaleMike...nanLily ... FemaleMike...nanLily ... FemaleMike...nanLily ... FemaleMike...nan

Program Optimization:
classInputImplementsrunnable{Resource R;  PublicInput (Resource r) { This. R =R; }        Public voidrun () {intx = 0;  while(true)           {                   if(x = = 0) {R.set ("Mike", "Nan"); }                      Else{R.set ("Lili", "Woman"); } x= (x + 1)% 2; }       }}classOutputImplementsrunnable{Resource R;  PublicOutput (Resource r) { This. R =R; }     Public voidrun () { while(true) {r.out (); }    }}classresource{PrivateString name; PrivateString sex; Private BooleanFlag =false;  Public synchronized voidset (String name,string sex) {if(flag)Try {             This. Wait (); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); }        This. Name =name;  This. Sex =sex; Flag=true;  This. Notify (); }       Public synchronized voidout () {if(!flag)Try {                 This. Wait (); } Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); } System.out.println (Name+ "...+" +sex); Flag=false;  This. Notify (); }   } Public classPerson { Public Static voidMain (string[] args) {Resource R=NewResource (); Input in=NewInput (R); Output Output=NewOutput (R); Thread T1=NewThread (in); Thread T2=NewThread (output);        T1.start ();    T2.start (); }}
Output:Mike...nanLily ... FemaleMike...nanLily ... FemaleMike...nanLily ... FemaleMike...nanLily ... FemaleMike...nanLily ... FemaleMike...nan

Java Inter-thread communication

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.