Java Code Example: waiting for thread to terminate (join)

With the join() method a thread A can wait for the termination of another thread B, e.g. to take over the result of B. join() thus blocks the further execution of A. If one does not want to wait an indefinite time, one can limit the waiting time by passing a maximum waiting time in milliseconds.

class ThreadExample extends Thread {
    public void run() {
        System.out.println("Start thread!");
        try {
            sleep(3000);
        } catch (java.lang.InterruptedException e) {
        }
        System.out.println("Thread terminated!");
    }
}

public class ThreadingExample {
    public static void main(String[] args) {
        ThreadExample t = new ThreadExample();

        t.start();

        try {
            t.join();
        } catch (java.lang.InterruptedException e) {
        }
    }
}
Output
Start thread!
Thread terminated!