Rendezvous and Timeouts

Problem

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

Solution

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

Discussion

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 will wait forever for the thread to terminate, while a version with arguments will wait up to the specified time. For a simple example, I’ll create (and start!) a simple thread that just reads from the console terminal, and the main thread will simply wait 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-7 is the code for the join( ) demo.

Example 24-7. Join.java

public 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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.