Searching...
Saturday, 22 March 2014

Java Thread Join() Example

11:58

1. ThreadJoinExample.java

package threading;
/**
 * <b>This class helps to understand the how Thread join() will work. I have a
 * scenario to execute the threads in order . Here i am creating 3 threads and
 * below are the execution order required</b>
 * 
 * <li>Thread 2 will start only after completion of thread 1</li> <li>Thread 3
 * will start only after completion of thread 2</li> <li></li> <li></li>
 * 
 * <li></li>
 * 
 * </ul>
 * 
 * @author vinod
 * 
 */
public class ThreadJoinExample {
	public static void main(String[] args) {
		Thread t1 = new Thread(new myThread1());
		Thread t2 = new Thread(new myThread2());
		Thread t3 = new Thread(new myThread3());
		try {
			t1.start();
			//Thread t2 will start only after completion of t1
			t1.join();
			t2.start();
			//Thread t3 will start only after completion of t2
			t2.join();
			t3.start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
class myThread1 implements Runnable {
	public void run() {
		System.out.println("Thread1 Started");
	}
}
class myThread2 implements Runnable {
	public void run() {
		System.out.println("Thread2 Started");
	}
}
class myThread3 implements Runnable {
	public void run() {
		System.out.println("Thread3 Started");
	}
}

2.Ouput



Thread1 Started
Thread2 Started
Thread3 Started


0 comments: