Java Thread Join method explanation with examples

thread join method

 144 total views

Today we will learn about the Java Thread join method and its different overloaded versions with full explanation using various scenarios.

As we all know, working on a multi-threaded environment is a tedious task and the execution order of thread is unpredictable but important for thread synchronization.

What is Thread.join() method?

Thread.join() method imposes current thread to wait until the thread on which join is called, completes its execution and goes to dead/terminated state.

For example, if in the main() method, we create a Thread object demoThread and execute demoThread.join() then the main method will pause its own execution and will wait for demoThread to complete its execution.

Always remember the Current Executing Thread will go to wait.

In the above example current thread is the main() method.

Example with and without using the join method

So now we will analyse the behaviour of threads in a multithreaded environment.

Starting with code without using join so that we will know what are the changes on using join() method.

First of all we need a Thread class so lets create it as the first step.

DemoThread.java

This thread class will be used for both the example.

public class DemoThread implements Runnable {

	@Override
	public void run() {
		System.out.println("Currently Running " +
	                             Thread.currentThread().getName());
	}
}

Code | Without the join method

public static void main(String[] args) {
		//Initializing thread objects
		Thread demoThread1 = new Thread(new DemoThread(), "Demo Thread - 1");
		Thread demoThread2 = new Thread(new DemoThread(), "Demo Thread - 2");
		Thread demoThread3 = new Thread(new DemoThread(), "Demo Thread - 3");
		
		//Starting Thread objects
		demoThread1.start();
		demoThread2.start();
		demoThread3.start();
		
		System.out.println("Main method- All threads are executed successfully");
		

	}

Output:

Main method- All threads are executed successfully
Currently Running Demo Thread - 3
Currently Running Demo Thread - 1
Currently Running Demo Thread - 2

Now as you can see in the above code, The main() method claims that It has successfully executed all the threads but In the Output, you can see all threads were executed after the main() method.
The correct output should be
1. All threads execute and print their message then
2. The main() method should print the success message.

Code | With the join method

In the below example, we will see the Java Thread Join method’s implementation.

public static void main(String[] args) {
		//Initializing thread objects
		Thread demoThread1 = new Thread(new DemoThread(), "Demo Thread - 1");
		Thread demoThread2 = new Thread(new DemoThread(), "Demo Thread - 2");
		Thread demoThread3 = new Thread(new DemoThread(), "Demo Thread - 3");
		
		//Starting Thread objects
		demoThread1.start();
		demoThread2.start();
		demoThread3.start();
		
		try {
			demoThread1.join();
		} catch (InterruptedException e) {
			System.out.println(demoThread1.getName() +" was interuppted");
		}
		
		try {
			demoThread2.join();
		} catch (InterruptedException e) {
			System.out.println(demoThread2.getName() +" was interuppted");
		}
		
		try {
			demoThread3.join();
		} catch (InterruptedException e) {
			System.out.println(demoThread3.getName() +" was interuppted");
		}
				
		System.out.println("Main method- All threads are executed successfully");
		
	}

Output:

Currently Running Demo Thread - 1
Currently Running Demo Thread - 3
Currently Running Demo Thread - 2
Main method- All threads are executed successfully

In the above code, the main method has initialized and started all the three threads but this time it has called join() method on each of the three Threads.

The main() method went in the waiting state until all the three threads execute their code and print the message.

Once all threads are finished then its right to say that all threads are executed successfully.

So now What is the execution order of all the threads?

The answer is Not Sure.

We have only made the main thread to finish after all the three threads i.e [main Thread] w.r.t [demoThread-1, demoThread-2, demoThread3].

These three threads can still run in any order among themselves.

So How can we also execute them in order?

Lets see below

public static void main(String[] args) {
		//Initializing thread objects
		Thread demoThread1 = new Thread(new DemoThread(), "Demo Thread - 1");
		Thread demoThread2 = new Thread(new DemoThread(), "Demo Thread - 2");
		Thread demoThread3 = new Thread(new DemoThread(), "Demo Thread - 3");
		
		//Starting Thread demoThread 1
		demoThread1.start();
		try {
			demoThread1.join();
		} catch (InterruptedException e) {
			System.out.println(demoThread1.getName() +" was interuppted");
		}
		System.out.println(demoThread1.getName()+ " finished");
		
		//Starting Thread demoThread 2
		demoThread2.start();
		try {
			demoThread2.join();
		} catch (InterruptedException e) {
			System.out.println(demoThread2.getName() +" was interuppted");
		}
		System.out.println(demoThread2.getName()+ " finished");
		
		//Starting Thread demoThread 3
		demoThread3.start();
		try {
			demoThread3.join();
		} catch (InterruptedException e) {
			System.out.println(demoThread2.getName() +" was interuppted");
		}
		System.out.println(demoThread3.getName()+ " finished");		
		
		System.out.println("Main method - All threads are executed successfully");
		
		System.out.println(Thread.currentThread()+ " finished");
		
	}

Output:

Currently Running Demo Thread - 1
Demo Thread - 1 finished
Currently Running Demo Thread - 2
Demo Thread - 2 finished
Currently Running Demo Thread - 3
Demo Thread - 3 finished
Main method - All threads are executed successfully
Thread[main,5,main] finished

As you can see from the above code and output that we have ensured java join method is called just after starting a Threads execution.

In this way the control comes back to main only when a thread finishes.

And you can say that the threads are in a order because we are running new thread only when the other one finishes.

** These threads are not running in parallel anymore

Pros of using the Join method

  • Can be used to impose order but then threads won’t be running in parallel
  • Use it if one threads output depends on another thread’s output

Cons of using the Join method

  • May impact parallelism of thread.
  • It can cause a thread to wait for unpredictable time.

Supported Overloaded methods

Java provides two variants of overloaded join() method

public final void join(long millis)
                throws InterruptedException
                
public final void join(long millis,
                       int nanos)
                throws InterruptedException

Using the above methods you can specify for How much time you want to wait for the thread to die.

The time is in milliseconds and a timeout of 0 means wait forever.

For example, if you give 1000 millisecond that means your current Thread will wait for 1 second (1 second == 1000 millisecond) before resuming its execution.

One Comment

  1. Thanks for complete explanation of join method. It helps a lot to me.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *