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 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 Finished."); } }
As you can see, it uses an
inner class
Runnable
(see Section 24.2) in
Thread
t
to be runnable.
3.15.189.199