join() Method

Thread class provides join() method. It is invoked by one thread on other thread to wait for the other thread to complete before proceeding. It will block the calling thread from becoming runnable till the other thread is alive. As shown in program below.

Implementation:
 // Joining_ok.java
class Task extends Thread
 {      Task(String name)
               {	setName(name);
	     }
	public void run()
	     {  for(int i=1;i<=2;i++)
		 {
		   System.out.println(“thread->”+getName()+” : “+i);
		 }	
	System.out.println(getName()+ “ : thread Finished....”);	
	 }
 }
public class Joining_ok
{   public static void main(String[] args) 
	{	
	    System.out.println(“Main thread Started...”);
		Task thrd=new Task(“Real Java”);
		thrd.start();
		try  
                  {  
		        thrd.join(); 
		  }
		catch(Exception ex)
		{
		 ex.printStackTrace(); 
		 }
		System.out.println(“Main thread Finished...”);
	}  
}
  Output
    Main thread Started...
    thread->Real Java : 1
    thread->Real Java : 2
    Real Java : thread Finished....
    Main thread Finished...

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
20 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android,MERN Stack(MongoDB,Express,ReactJS,NodeJS). If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : bcebti@gmail.com #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap