join():
- join() is pre-defined method in Thread class.
- It is non static method hence we call on Thread object.
- Stop current thread execution until joined thread execution completed.
class Custom extends Thread
{
public void run()
{
for (int i=1 ; i<=10 ; i++)
{
System.out.println("Custom : " + i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){ }
}
}
}
class Default
{
public static void main(String[] args) throws Exception
{
System.out.println("Starts @ Default thread");
Custom t = new Custom();
t.start();
t.join();
System.out.println("Ends @ Default thread");
}
}
import java.util.Scanner ;
class Calculate extends Thread
{
static int sum;
public void run()
{
System.out.println("Calc starts...");
Calculate.sum=0;
for (int i=1 ; i<=SumOfN.n ; i++)
{
Calculate.sum = Calculate.sum+i;
}
System.out.println("Calc ends...");
}
}
class SumOfN
{
static int n ;
public static void main(String[] args) throws Exception
{
Scanner scan = new Scanner(System.in);
System.out.println("Sum of First N numbers Code");
System.out.print("Enter n val : ");
SumOfN.n = scan.nextInt();
Calculate calc = new Calculate();
calc.start();
calc.join();
System.out.println("Sum value is : " + Calculate.sum);
}
}