Advertisement



< Prev
Next >



Joining of Thread - join() method




The join() method of Thread class is a very useful method in a situation when we want a thread to wait for another thread to finish its execution. The name join() comes from a concept of making a thread wait until a specific thread joins it after finishing its execution.




Let's understand join() method with a short code:


public static void main(String... ar)
{
	Thread newThread = new Thread("Thread2"); //line1
	newThread.start(); 			  //line2
	newThread.join();			  //line3
	System.out.println("Hello from the main method");
}


Code Analysis


The code is inside the main() method, hence, the main thread(default thread) runs automatically.




There are two versions of join() method -:


Method Description
final void join()
This version of join() method makes a thread wait for another thread to finish its execution.

final void join(long millis)
This version of join() method a thread wait only for a specified time(in milliseconds) for another thread to finish its execution.






Let's understand join() method by an example:


//Java - Example of join() method
 

class ThJoin implements Runnable
{

public void run()  //Entry Point of the new thread.
{
	Thread th=Thread.currentThread(); //Getting the reference to the currently executing thread.
	try	
	{
		for(int i=0;i<3;i++)
		{
			Thread.sleep(1000); //This will make this thread sleep for 1000 ms.
			System.out.println(i);	
		}
		System.out.println(th.getName() + " completed");			
	}
	catch(InterruptedException e)
	{
		System.out.println("Thread Interrupted" + e);
	}
}


public static void main(String... ar)
{
	ThJoin newTh= new ThJoin();
	Thread th= new Thread(newTh, "Other Thread");//Calling Thread's constructor & passing the object
						    //of class that  implemented  Runnable interface
						    //& the name of new thread.
	
	//Starting the new thread, calls the run() method automatically
	th.start();

	try
	{
		th.join(); //main thread will wait for other thread to complete its execution and join it.

		System.out.println("Main thread completed");
	}
	catch(InterruptedException e)
	{
		System.out.println(e);
	}
}
}


Output is - :


0
1
2
Other Thread completed
Main thread completed



Advertisement




Program Analysis


The code is inside the main() method, hence, the main thread(default thread) runs automatically.



Please share this article -




< Prev
Next >
< Thread Priorities
IllegalThreadStateException >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement