Java Thread Programming 1.8.3-Inter-thread Communication

Source: Internet
Author: User
  CubbyHole Example  The class CubbyHole (see Listing 8.9) simulates a cubbyhole. A cubbyhole is a slot that can have only one item in it at a time. one thread puts an item into the slot and another thread takes it out. if a thread tries to put an item into a cubbyhole that is already occupied, the thread blocks until the slot is available. if a thread tries to remove an item from an empty cubbyhole, the thread blocks Until an item is added. in this example, the slot is a reference to an object. this technique allows objects to be handed off from one thread to another in a thread-safe manner. cubbyHole refers to a channel, which can accommodate only one thing at a time, one thread is put, and the other thread is retrieved. If something already exists, it cannot be placed until it is taken out. If there is nothing, you cannot take it until it is put into the new thing. The following is a thread-safe solution: CubbyHole. java /** Created on 2005-7-14 ** Java Thread Programming-Paul Hyde * Copyright? 1999 Sams Publishing * Jonathan Q. bo Study Notes **/package org. tju. msnrl. jonathan. thread. chapter8;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: 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) throws InterruptedException {print ("putIn ()... begin "); While (this. obj! = Null ){// Wait until the data is taken out print ("Putin () Wait... begin "); Wait ();Print ("Putin () Wait... end");} This. OBJ = OBJ; // Add a new object Policyall (); // Notify other threads: an object can be printed ("Putin ()... end ");} public synchronized object takeout () throws interruptedexception {print (" takeout ()... begin "); While (obj = null ){// Wait until there is data available for print ("takeout () Wait... begin "); Wait ();Print ("takeout () Wait... end");} object temp = OBJ; Obj = null;// Clear the original data Policyall ();// Notify other threads: the data has been taken out. You can enter the new data print ("takeout ()... end "); Return temp;} public void print (string MSG) {string temp = thread. currentthread (). getname (); system. out. println (temp + "-" + MSG );}} CubbyHoleMain. java/** Created on 2005-7-14 ** Java Thread Programming-Paul Hyde * Copyright? 1999 Sams Publishing * Jonathan Q. bo Study Notes **/package org. tju. msnrl. jonathan. thread. chapter8;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: jonathan.q.bo@gmail.com * Blog: blog.csdn.net/jonathan_q_bo * blog.yesky.net/jonathanundersun ** Enjoy Life with Sun! **/Public class CubbyHoleMain {public static void print (String msg) {String temp = Thread. currentThread (). getName (); System. out. println (temp + "-" + msg);} public static void main (String [] args) {final CubbyHole ch = new CubbyHole (); Runnable runA = new Runnable () {public void run () {try {Thread. sleep (500); // deliberately executed later, so that other threads can obtain the data String str; str = "multithreads"; ch. putIn (str); // 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 () ;}}; Runnable runB = new Runnable () {public void run () {try {Object obj; obj = ch. takeOut (); print ("run () takeOut ()" + obj ); Thread. sleep (500 );// First fetch and then save Obj = ch. takeOut (); // 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-takeOut ()... endthreadB-run () takeOut () multithreadsthreadA-run () putIn () multithreadsthreadA-putIn ()... beginthreadA-putIn ()... endthreadA-run () putIn () programmingthreadA-putIn ()... beginthreadA-putIn () wait... beginthreadB-takeOut ()... beginthreadB-takeOut ()... endthreadB-run () takeOut () programmingthreadB-takeOut ()... beginthreadB-takeOut () wait... beginthreadA-putIn () wait... endthreadA-putIn ()... endthreadA-run () putIn () with javathreadB-takeOut () wait... endthreadB-takeOut ()... endthreadB-run () takeOut () with java Using join () to Wait for a Thread to Die  The join () method of Thread can be used to cause the current thread to block waiting for the specified thread to die. this is a relatively crude form of inter-thread communication, but on occasion it can be useful. if threadX runs the code join () method blocks the current thread until the specified Thread dies. Try { ThreadY. join () } Catch (InterruptedException x ){ }  ThreadX will block waiting for threadY to die. if threadX is interrupted while inside join (), it will throw an InterruptedException. there are three versions of the join () method available in Thread, all of which are public: join (), join (long), and join (long, int ). additionally, none of these methods can be overridden in a subclass because they are all declared final.  In the Thread class, three functions are provided: join (), join (long), join (long, int), all of which are declared as final and cannot be quilt class override.   Join ()  Public final void join () throws InterruptedException The join () method causes the current thread to block and wait an unlimited amount of time for this thread to die. the current thread will throw an InterruptedException if interrupted while waiting for the specified thread to die. join () blocks the current thread until it dies. If it is interrupted while waiting, InterruptedException will be thrown. Join (long)Public final synchronized void join (long msTimeout) throws InterruptedException, IllegalArgumentException // RuntimeException  The join (long) method causes the current thread to block and wait up to msTimeout milliseconds for the specified thread to die. if msTimeout is 0, the current thread will never time out and will wait forever for the specified thread to die (just like join ()). if msTimeout is less than 0, an IllegalArgumentException is thrown. the current thread will throw an InterruptedException if interrupted while waiting for the specified thread to die.  Join (long) blocks the current thread for a certain period of time (milliseconds) and waits for it to die. If the set time is 0, the infinite wait will not time out. If the parameter is smaller than 0, an IllegalArgumentException exception will be thrown.   Join (long, int)  Accurate to nanoseconds. This method is not implemented by virtual machines.   JoinDemo  /** Created on 2005-7-14 ** Java Thread Programming-Paul Hyde * copyright? 1999 SAMs publishing * Jonathan Q. bo Study Notes **/package Org. tju. msnrl. jonathan. thread. chapter8;/*** @ author Jonathan Q. bo from tju msnrl ** E-mail: 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 returns the newly generated thread */public static thread launch (string name, long naptime) {final long sleeptime = naptime; runnable run = new runnable () {public void run () {try {print ("Run ()... begin "); thread. sleep (sleeptime);} catch (interruptedexception e) {print ("interrupted");} finally {print ("Run ()... end ") ;}}; threa D thread = new thread (run, name); thread. start (); // start to execute return thread;} public static void print (string MSG) {string temp = thread. currentthread (). getname (); system. out. println (temp + "-" + MSG);} public static void main (string [] ARGs) {thread [] T = new thread [3]; T [0] = launch ("threada", 2000); t [1] = launch ("threadb", 1000); t [2] = launch ("threadc ", 3000); For (INT I = 0; I <t. length; I ++) {try {String Index = "t [" + I + "]"; 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");} 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 2000 msmain-threadB is alive? Falsemain-threadB begin joinmain-threadB end join, costs 0 msmain-threadC is alive? Truemain-threadC begin jointhreadC-run ()... endmain-threadC end join, costs 1000 ms  

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.