A brief usage of the join method on class Thread

 

java

 

The java docs defines the usage of the Thread#join method as "Waits for this thread to die."  

 

I would like to expand on this definition.

 

 

public class Hello {

    public static void main(String[] args) throws InterruptedException {

        Thread one = new Thread(new WorkerOne());
        one.start();
        System.out.println("Finishing main.");
    }

    private static class WorkerOne implements Runnable {

        @Override
        public void run() {
            try {
            System.out.println("Starting one");

             Thread.sleep(3000);

            System.out.println("Talking from One");
             Thread.sleep(1000);
            System.out.println("Leaving One");
            } catch (InterruptedException e) {

            }
        }
    }

}

 

 

Take a look at the code snippet above. On my JVM, executing this program results in the following output:


 

Starting one Finishing main. 
Talking from One 
Leaving One 


 

 

Adding a join call on thread one would result in the output below:

 

        Thread one = new Thread(new WorkerOne());
        one.start();
        one.join(); //Adding join
        System.out.println("Finishing main.");

 

Out put:
 

Starting one 
Talking from One 
Leaving One 
Finishing main. 

 

You can see that the main thread waited for thread one to finish before executing its print out statement.

The join method on the Thread class could be used in this way for a more complex program.

I guess we could say that calling a join on a thread would make the current thread that calls it wait until the join thread finishes executing.

I hope this example clarifies its usage.