Recipe 24.4 Rendezvous and Timeouts


You need to know whether something finished or whether it finished in a certain length of time.


Start that "something" in its own thread and call its join( ) method with or without a timeout value.


The join( ) method of the target thread is used to suspend the current thread until the target thread is finished (returns from its run method). This method is overloaded; a version with no arguments waits forever for the thread to terminate, while a version with arguments waits up to the specified time. For a simple example, I create (and start!) a simple thread that just reads from the console terminal, and the main thread simply waits for it. When I run the program, it looks like this:$ java Join Starting Joining Reading hello from standard input # waits indefinitely for me to type this line Thread Finished. Main Finished.$

Example 24-8 lists the code for the join( ) demo.

Example 24-8.
public class Join {     public static void main(String[] args) {         Thread t = new Thread( ) {             public void run( ) {                 System.out.println("Reading");                 try {            );                 } catch ( ex) {                     System.err.println(ex);                 }                 System.out.println("Thread Finished.");             }         };         System.out.println("Starting");         t.start( );         System.out.println("Joining");         try {             t.join( );         } catch (InterruptedException ex) {             // should not happen:             System.out.println("Who dares interrupt my sleep?");         }         System.out.println("Main Finished.");     } }

As you can see, it uses an inner class Runnable (see Recipe 24.1) in Thread t to be runnable.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: