join():
- An instance method belongs to Thread class.
- It stops the current the thread execution until joined thread execution completes.
For Example,
Consider First thread is calculating sum of first N numbers and second thread has to display the result. The Second thread has to wait until First thread completes calculation.

import java.util.Scanner; class Main { static int n; public static void main(String[] args) { System.out.println(“***Sum of First N numbers***”); Scanner sc = new Scanner(System.in); System.out.print(“Enter n val : “); Main.n = sc.nextInt(); Calc thread = new Calc(); thread.start(); try { thread.join(); } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println(“Sum value : ” + Calc.sum); } } class Calc extends Thread { static int sum=0; public void run() { for (int i=1 ; i<=Main.n ; i++) { Calc.sum = Calc.sum+i; } } } |