ProblemYou need to know whether something finished or whether it finished in a certain length of time. SolutionStart that "something" in its own thread and call its join( ) method with or without a timeout value. DiscussionThe 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: darwinsys.com$ java Join Starting Joining Reading hello from standard input # waits indefinitely for me to type this line Thread Finished. Main Finished. darwinsys.com$ Example 24-8 lists the code for the join( ) demo. Example 24-8. Join.javapublic class Join { public static void main(String[] args) { Thread t = new Thread( ) { public void run( ) { System.out.println("Reading"); try { System.in.read( ); } catch (java.io.IOException 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. |