join() method in Java Thread : The join() method of a Thread class allows the current thread to wait until the thread in which it is called will die. Sometime a question is asked in the interviews that How can we make sure main() is the last thread to finish in Java Program? So the answer is here that the join() method is give to the way to confirm that all the child threads are finished execution before main thread terminated.
There are three overloaded join functions:
- public final void join(): This method pause the current thread until the thread on which its
called is terminated.If in any case the current thread is interrupted It throws InterruptedException.
- public final synchronized void join(long millis): This method is used to pause the thread on which its called to be terminated(dead) or wait for specified milliseconds.It is not guarantee that the thread will wait for specified time, it may be more execution of thread totally depend OS.
- public final synchronized void join(long millis, int nanos): This method is used to pause the current thread for given milliseconds plus nanoseconds.
Thread Join Example :
package com.evon.threads;
public class ThreadJoinSample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread1");
Thread t2 = new Thread(new MyRunnable(), "Thread2");
Thread t3 = new Thread(new MyRunnable(), "Thread3");
t1.start();
//start second thread after waiting for 1 seconds or if it's dead
try {
t1.join(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
//start third thread only when first thread is dead
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
//let all threads finish execution before finishing main thread
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads are dead, exiting main thread");
}
}
MyRunnable.java
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("Thread started :"+Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread ended :"+Thread.currentThread().getName());
}
}
Output :
Thread started :Thread1
Thread started :Thread2
Thread ended :Thread1
Thread started :Thread3
Thread ended :Thread2
Thread ended :Thread3
All threads are dead, exiting main thread
0 Comment(s)