Ensure Main Method Exit at the End

Spread the love

We can achieve this by isAlive() and join() methods of Thread class. isAlive() is not great at doing this task. So, we will be using join() method.

Threadd class — implements Runnable : 

class Threadd implements Runnable{
Thread t;
String name;

Threadd(){
name = “how”;
t = new Thread(this,name);
System.out.println(“This is thread”);
t.start();
}

public void run() {
for(int i=0;i<20;i++){
System.out.println(“This is run method”);
try{
Thread.sleep(100);
}
catch(InterruptedException e){}
}
}
}

Main Class : 

class Main{
public static void main(String args[])throws InterruptedException{
Threadd t0 = new Threadd();
Threadd t1 = new Threadd();
Threadd t2 = new Threadd();

try {
t0.t.join();
t1.t.join();
t2.t.join();
}
catch (InterruptedException e){}
System.out.println(“Main Exit”);
}
}

When you will comment the try-catch block in main method, you will see that main method will exit before other threads.