Java Concurrency – join() method


The join function

This function is used to join the beginning of the execution of a thread to the end of the execution of another thread. This way, it is ensured that the first thread won’t run until the second thread has stopped executing. This function waits for a specific number of milliseconds for the thread to terminate.

Let us see an example −

Example

 Live Demo

import java.lang.*;
public class Demo implements Runnable{
   public void run(){
      Thread my_t = Thread.currentThread();
      System.out.println("The name of the current thread is " + my_t.getName());
      System.out.println("Is the current thread alive? " + my_t.isAlive());
   }
   public static void main(String args[]) throws Exception{
      Thread my_t = new Thread(new Demo());
      System.out.println("The instance has been created and started");
      my_t.start();
      my_t.join(30);
      System.out.println("The threads will be joined after 30 milli seconds");
      System.out.println("The name of the current thread is " + my_t.getName());
      System.out.println("Is the current thread alive? " + my_t.isAlive());
   }
}

Output

The instance has been created and started
The threads will be joined after 30 milli seconds
The name of the current thread is Thread-0
The name of the current thread is Thread-0
Is the current thread alive? true
Is the current thread alive? true

A class named Demo implements the Runnable class. A ‘run’ function is defined that assigns the current thread as a newly created Thread. In the main function, a new instance of the thread is created, and is it begun using the ‘start’ function. This thread is joined with another thread after a specific amount of time. The relevant messages are displayed on the screen.

Updated on: 04-Jul-2020

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements