The join function −
The join method makes sure that the current thread waits until the thread it is supposed to join with has been terminated. This function waits until the thread on which the function was called, has been terminated.
Syntax
final void join() throws InterruptedException
Let us see an example −
Example
public class Demo extends Thread{ public void run(){ System.out.println("sample "); try{ Thread.sleep(10); } catch (InterruptedException ie){ } System.out.println("only "); } public static void main(String[] args){ Demo my_obj_1 = new Demo(); Demo my_obj_2 = new Demo(); my_obj_1.start(); System.out.println("The first object has been created and started"); try{ System.out.println("In the try block, the first object has been called with the join function"); my_obj_1.join(); } catch (InterruptedException ie){ } System.out.println("The second object has been started"); my_obj_2.start(); } }
Output
The first object has been created and started In the try block, the first object has been called with the join function sample only The second object has been started sample only
A class named Demo extends the Thread class. Here, a ‘run’ function is defined wherein a try catch block is defined. Here, in the try block, the sleep function is called and the catch block is left empty. In the main function, two instances of the Demo object are created. The first object is stated and it is called using the ‘join’ function. The same is done with the second object as well and messages are relevantly displayed.