You can call the join
method on a Thread
object to wait for it to finish. Example:
public class JoinTest implements Runnable {
public static void main(String[] args) throws Exception {
System.out.println("in main");
Thread secondThread = new Thread(new JoinTest());
secondThread.start();
secondThread.join();
System.out.println("join returned");
}
@Override
public void run() {
System.out.println("second thread started");
// wait a few seconds for demonstration purposes
try {
Thread.sleep(3000);
} catch(InterruptedException e) {}
System.out.println("second thread exiting");
}
}
Note: it doesn't matter whether you choose to extend Thread or implement Runnable for this - any Thread
object can be joined.
The output should be:
in main
second thread started
and then 3 seconds later:
second thread exiting
join returned