Java Thread Programming 1.8.3-inter-thread Communication

Source: Internet
Author: User
Tags empty end execution final getmessage net sleep string
Cubbyhole example the class Cubbyhole (Listing 8.9) simulates a cubbyhole. A cubbyhole is a slot this can have only one item in it. One thread puts an item into the slot and another thread takes it out. The thread blocks until the slot is available, If a thread tries to put a cubbyhole this is already occupied. If a thread tries to remove the empty cubbyhole, the thread blocks until an item is added. In this example, the slot are a reference to an object. This technique allows objects is handed off from one thread to another in a thread-safe manner. cubbyhole refers to a channel in which a Time can only hold one thing, one thread put, another thread to take. If you have something, you can't put it on until something is taken out. If you don't have anything, you can't take it until you put something new in it. A thread-safe solution is given below:  cubbyhole.java/* * Created on 2005-7-14 * * java thread Programming-paul Hyde & nbsp;* Copyright? 1999 Sams publishing * Jonathan Q-Bo Learning notes  *  */package org.tju.msnrl.jonathan.thread.chapter8; /* * * @author Jonathan Q. Bo from Tju msnrl * * email:jonathan.q.bo@gmail.com * blog:blog.csdn.net/jonathan_q_bo *       blog.yesky.net/jonathanundersun *  * Enjoy Life with sun! *  */public class Cubbyhole {     private Object obj;     public cubbyhole () {         obj = null;   }        public synchronized void PutIn (Object obj) th Rows interruptedexception{        Print ("PutIn () ... begin");                 while (this.obj!= null) {//wait until data is removed              Print ("putIn () wait ... begin");             Wait ();             Print ("putIn () Wait ... end");       }                this.obj = obj;//Add New Object          notifyall ()//Notify other Threads: Object preferable                  Print ("PutIn () ... end");   }        Public synchronized Object Takeout () throws interruptedexception{        print (" Takeout ();                while ( obj = = null) {//wait until there is data to fetch             print ("takeout () ... begin ");            wait ();             Print ("takeout () Wait ... end");        }                Object temp = obj;        obj = null;//Empty The original data          notifyall ()//Notify other threads: Data has been removed, new data can be filled                  Print ("takeout () ... end");                 return temp;   }        public void print (String msg) {         string temp = Thread.CurrentThread (). GetName ();         System.out.println (temp + "-" + msg);   }  } cubbyholemain.java/*& nbsp;* Created on 2005-7-14 * * Java Thread programming-paul Hyde  * Copyright? 1999 Sams publishing * Jonathan Q-Bo Learning notes  *  */package org.tju.msnrl.jonathan.thread.chapter8; /* * * @author Jonathan Q. Bo from Tju msnrl * * email:jonathan.q.bo@gmail.com * Blog:blog.csdn.net/jonathan_q_bo *      blog.yesky.net/jonathanundersun *  * Enjoy Life with sun! *  */public class Cubbyholemain {        public Stat IC void Print (String msg) {        String temp = Thread.CurrentThread (). GetName (); nbsp;       System.out.println (temp + "-" + msg);   }      public static void Main (string[] args) {        final cubbyhole ch = new C Ubbyhole ();                Runnable Runa = New Runnable () {          public void run () {               try{                   Thread.Sleep (500); intentionally late some execution, let the other lineProcess first FETCH data                   String str;                                     Str= "Multithreads";                   ch.putin (str)//Can be kept                    Print ("Run () putIn ()" + str);                                      str = "Programming";                   ch.putin (str);                   Print ("Run () putIn ()" + str);                                      str = "with Java";                   ch.putin (str);                   Print ("Run () putIn ()" + str);                                 }catch (interruptedexception e) {                   Print ("exception" + E.getmessage ());             }  & nbsp;      }       };                 Runnable Runb = new Runnable () {             public void Run () {                 try{                     Object obj;                                          obj = ch.takeout ();                     Print ("Run () takeout ()" + obj);                                          Thread.Sleep (500);//First Take, after save                                           obj = ch.takeout ()//can always take                      print ("Run () takeout ( ) "+ obj";                                          obj = ch.takeout ();                     Print ("Run () takeout ()" + obj);                                     }catch (interruptedexception e) {                     Print ("exception" + E.getmessage ());               }            }       } ;                Thread Threada = new Thread ( Runa, "Threada");        Threada.start ();                 Thread threadb = new Thread (RUNB, "threadb");         Threadb.start ();   }}  output Result: Threadb-takeout () ... beginthreadb-tAkeout () Wait ... beginthreada-putin () ... beginthreada-putin () ... endthreadb-takeout () wait ... Endthreadb-takeo UT () ... endthreadb-run () takeout () Multithreadsthreada-run () putIn () Multithreadsthreada-putin () ... Beginthreada- Putin () () Endthreada-run () Putin () Programmingthreada-putin () ... beginthreada-putin () wait ... beginthreadb-ta Keout () ... beginthreadb-takeout () ... endthreadb-run () takeout () programmingthreadb-takeout () ... Beginthreadb-ta Keout () Wait ... beginthreada-putin () wait ... endthreada-putin () ... endthreada-run () putIn () with Javathreadb-ta Keout () Wait ... endthreadb-takeout () ... endthreadb-run () takeout () with java  using join () to wait for a T Hread to Die the Join () method of thread can is used to cause the current Thread to block waiting for the specified t Hread to die. This is a relatively crude form of inter-thread communication and but on occasion it can be useful. If THREADX runs the Code join (method causes the current thread to block until the specified thread dies.  try {    thready.join ()} catch (Interruptedexception x) {}&NBSP;THREADX'll block waiting for thre Ady to die. If ThreadX is interrupted while inside join (), it would throw an interruptedexception. There are three versions of the join () method available in Thread, all of which are public:join (), join (long), and join (l Ong, int). Additionally, none of the methods can be overridden in a subclass because they are all declared final.  the thread class, provide Three functions: Join (), join (long), join (Long,int), all declared final, not quilt class Override join ()  public final void join ()          throws Interruptedexception the Join () method causes the current thread to Block and wait a unlimited amount of time for this thread to die. The current thread would throw an interruptedexception if interrupted while waiting for the specified thread to Die. j Oin () blocks the current thread until it dies, and if the wait is interrupted, it throws Interruptedexception join (long)  publicFinal synchronized void join (long mstimeout)         throws Interruptedexception,                illegalargumentexception      //Runtimeexception the Join (Long) method causes the current thread Up to mstimeout milliseconds for the specified thread to die. If mstimeout is 0, the current thread would never time out and would wait forever for the specified thread to die (just like Join ()). If Mstimeout is less than 0, a illegalargumentexception is thrown. The current thread would throw an interruptedexception if interrupted while waiting for the specified thread to Die. j Oin (long) causes the current thread to block for a certain amount of time (milliseconds) waiting for it to die, if the setting time is 0, the infinite wait does not timeout, and if the argument is less than 0, the illegalargumentexception exception  join (long, int) is thrown.   Accurate to nanosecond, the general virtual machine does not implement this method  joindemo /* * Created on 2005-7-14 * * Java Thread Programming-paul Hyde  * Copyright? 1999 Sams Publishing * Jonathan Q. Bo Learning notes  *  */package org.tju.msnrl.jonathan.thread.chapter8; /** * @author Jonathan Q. Bo from Tju msnrl * * email:jonathan.q.bo@gmail.com * Blog:blog.csdn.net/jonathan_q_bo  *      blog.yesky.net/jonathanundersun *  * Enjoy Life with sun! *  */ public class Joindemo {       /**     * generates a thread       * @param name Thread name      * @param naptime thread survival time      * @return return The newly generated thread      */    public static thread launch (String name, long naptime) {         final Long sleeptime = naptime;                Runnable Run = new Runnable () {           public void Run () {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;     try{                   Print ("Run () ... begin");                   Thread.Sleep (sleeptime);              }catch (interruptedexception e) {                   print ("interrupted");              }finally{                   Print ("Run () ... end");              }         }        };               &nbsP Thread thread = new Thread (run,name);        Thread.Start ()//Start execution                  return thread;   }         public static void print (String msg) {        String temp = Thread.CurrentThread (). GetName ();        System.out.println (temp + "-" + msg);   }        public static void Main (string[] args) { &nbsp ;              thread[] t = new thread[3];         t[0] = launch ("Threada", Watts);        t[1] = Launch ("THREADB", 1000);        t[2] = launch ("THREADC", 3000);                 for (int i = 0; i < t.length; i++) {            try{                 String index = "t[" + i + "]";      & nbsp;         String name = T[i].getname ();                 Print (name + "is alive?" + t[i].isalive ());                                 Print (name + "begin join");                 Long starttime = System.currenttimemillis ();                 t[i].join ();                 Long endtime = System.currenTtimemillis ();                print (name + " End join, costs "+ (Endtime-starttime) +" MS ");            & nbsp;              }catch (interruptedexception e) {                E.printStackTrace ();           }                    }   }    }  output Result: Main-threada is alive? Truemain-threada begin Jointhreada-run () ... beginthreadb-run () ... beginthreadc-run () ... beginthreadb-run (). . Endthreada-run () ... Endmain-threada end join, costs 2000MSMAIN-THREADB is alive? FALSEMAIN-THREADB begin JOINMAIN-THREADB End join, costs 0msmain-THREADC is alive? TRUEMAIN-THREADC begin Jointhreadc-run () ... endmain-threadc end join, costs 1000ms

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.