Home » Java programs

Java program to Join Threads

In this article we will learn how to join threads? This program is going to be implemented using join() method of Thread class.
Submitted by Jyoti Singh, on December 04, 2017

Java Thread class provides a method join() - this method is to check or wait for a thread to die, when this method is invoked on a thread the current thread will stop and wait till the thread (on which the join method is invoked) complete its execution.

Here, we have three threads T1, T2, T3 and join() method is invoked on thread T1, T2. T3 threads will not start until T1 finishes its execution or dead.

Program to join threads in java

public class JoinThread extends Thread {
	/*run() method is responsible for running a thread,
	all the programming logic will be contain by this thread 
	i.e what u want your thread to do */

	public void run() {
		for(int i=1;i<=5;i++){
			try {
				/*sleep method is to stop the current for a particular time 
				u can take it as a pause and restart a thread will pause for 
				a specific time say 500ms (meanwhile the next thread will 
				start its execution) and then restart*/

				Thread.sleep(500);
			} 
			catch (InterruptedException e) {
				System.out.println(e);
			}
			System.out.println(i);
		}
		super.run();
	}

	public static void main(String[] args) {
		//Thread objects
		JoinThread T1=new JoinThread();
		JoinThread T2=new JoinThread();
		JoinThread T3=new JoinThread();
		//start thread T1
		T1.start();
		try {
			/* join() method waits for a thread to die, here join method 
			will wait for thread T1 to complete its execution and die after 
			that the execution of thread T2 will start*/
			T1.join();
		} 
		catch (InterruptedException e) {
			System.out.println(e);
		}
		T2.start();
		T3.start();
	}
}

Output

1
2
3
4
5
1
1
2
2
3
3
4
4
5
5


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.