Joining Threads In Java

The Java programming language offers the join method through the java.lang.Thread class, allowing one thread to wait for another thread to complete its execution. If th represents the Thread object currently running, invoking th.join; ensures that th finishes its task before the program proceeds to the next step. When multiple threads use the join method, it results in method overloading, enabling developers to specify a waiting period. However, like the sleep method in Java, the behavior of join also relies on the operating system for timing, so the actual waiting time may differ from what is specified in the parameters. Below are three variations of the overloaded join method.

Description of The Overloaded join Method

The join method pauses the current thread's execution and transitions it into a waiting state. The current thread stays in this waiting state until the thread that triggered the join method finishes and reaches its terminated state. If the thread is interrupted during this process, it will raise an InterruptedException.

Syntax:

Example

public final void join() throws InterruptedException

The method join(long mls) causes the current thread to pause its execution and enter a waiting state. The current thread will stay in this state until the specified thread finishes its task or until the defined time duration (in milliseconds) elapses.

Syntax:

Example

public final synchronized void join(long mls) throws InterruptedException, where mls is in milliseconds

When the join(long milliseconds, int nanoseconds) method is called, the current thread pauses its execution and enters a waiting state. The current thread stays in this waiting state until the thread on which the join method is called finishes its execution or the specified period of time (combining milliseconds and nanoseconds) elapses.

Syntax:

Example

public final synchronized void join(long mls, int nanos) throws InterruptedException, where mls is in milliseconds.

Example of join Method in Java

The program below demonstrates how to utilize the join method.

FileName: ThreadJoinExample.java

Example

// A Java program for understanding 
// the joining of threads

// import statement
import java.io.*;

// The ThreadJoin class is the child class of the class Thread
class ThreadJoin extends Thread
{
// overriding the run method
public void run()
{
for (int j = 0; j < 2; j++)
{
try
{
// sleeping the thread for 300 milli seconds
Thread.sleep(300);
System.out.println("The current thread name is: " + Thread.currentThread().getName());
}
// catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught: " + e);
}
System.out.println( j );
}
}
}

public class ThreadJoinExample
{
// main method
public static void main (String argvs[])
{

// creating 3 threads
ThreadJoin th1 = new ThreadJoin();
ThreadJoin th2 = new ThreadJoin();
ThreadJoin th3 = new ThreadJoin();

// thread th1 starts
th1.start();

// starting the second thread after when
// the first thread th1 has ended or died.
try
{
System.out.println("The current thread name is: "+ Thread.currentThread().getName());

// invoking the join() method
th1.join();
}

// catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}

// thread th2 starts
th2.start();

// starting the th3 thread after when the thread th2 has ended or died.
try
{
System.out.println("The current thread name is: " + Thread.currentThread().getName());
th2.join();
}

// catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}

// thread th3 starts
th3.start();
}
}

Output:

Output

The current thread name is: main
The current thread name is: Thread - 0
0
The current thread name is: Thread - 0
1
The current thread name is: main
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1

In the provided code snippet, it is demonstrated that the initiation of the second thread, th2, occurs subsequent to the completion of the initial thread, th1. Furthermore, the thread th3 commences its execution only after the termination of the second thread, th2.

The Join Method: InterruptedException

In the previous section discussing the join method, we discovered that if a thread is interrupted, it will result in an InterruptedException being thrown. The illustration below demonstrates this scenario.

FileName: ThreadJoinExample1.java

Example

class ABC extends Thread
{
Thread threadToInterrupt;
// overriding the run() method
public void run()
{
// invoking the method interrupt
threadToInterrupt.interrupt();
}
}


public class ThreadJoinExample1
{
// main method
public static void main(String[] argvs)
{
try
{
// creating an object of the class ABC
ABC th1 = new ABC();

th1.threadToInterrupt = Thread.currentThread();
th1.start();

// invoking the join() method leads 
// to the generation of InterruptedException
th1.join();
}
catch (InterruptedException ex)
{
System.out.println("The exception has been caught. " + ex);
}
}
}

Output:

Output

The exception has been caught. java.lang.InterruptedException

Some More Examples of the join Method

Let' see some other examples.

Filename: TestJoinMethod1.java

Example

class TestJoinMethod1 extends Thread{  
 public void run(){  
  for(int i=1;i<=5;i++){  
   try{  
    Thread.sleep(500);  
   }catch(Exception e){System.out.println(e);}  
  System.out.println(i);  
  }  
 }  
public static void main(String args[]){  
 TestJoinMethod1 t1=new TestJoinMethod1();  
 TestJoinMethod1 t2=new TestJoinMethod1();  
 TestJoinMethod1 t3=new TestJoinMethod1();  
 t1.start();  
 try{  
  t1.join();  
 }catch(Exception e){System.out.println(e);}  
  
 t2.start();  
 t3.start();  
 }  
}

Output:

Output

1
       2
       3
       4
       5
       1
       1
       2
       2
       3
       3
       4
       4
       5
       5

In the example shown above, once task t1 finishes its execution, tasks t2 and t3 will commence running.

join(long miliseconds) Method Example

Filename: TestJoinMethod2.jav

Example

class TestJoinMethod2 extends Thread{  
 public void run(){  
  for(int i=1;i<=5;i++){  
   try{  
    Thread.sleep(500);  
   }catch(Exception e){System.out.println(e);}  
  System.out.println(i);  
  }  
 }  
public static void main(String args[]){  
 TestJoinMethod2 t1=new TestJoinMethod2();  
 TestJoinMethod2 t2=new TestJoinMethod2();  
 TestJoinMethod2 t3=new TestJoinMethod2();  
 t1.start();  
 try{  
  t1.join(1500);  
 }catch(Exception e){System.out.println(e);}  
  
 t2.start();  
 t3.start();  
 }  
}

Output:

Output

1
       2
       3
       1
       4
       1
       2
       5
       2
       3
       3
       4
       4
       5
       5

Upon completion of its task for 1500 milliseconds (3 times) as shown above, t1 triggers the execution of t2 and t3.

Input Required

This code uses input(). Please provide values below: