< 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 main");
}


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


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, "OtherThread");//Calling Thread's constructor & passing the object
					    //of class that  implemented  Runnable interface
					    //& the name of new thread.
th.start();

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

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


}
}


Output is - :


0
1
2
Other Thread completed
Main thread completed


Program Analysis


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



Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter



< Prev
Next >
< Thread Priorities
IllegalThreadStateException >
Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
Python

Ad2