Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata