Tags
The join() method in Thread Class allows one thread to wait for completion of another thread. For example:
t.join();
The above code will take the current thread in execution and join behind the thread referred by ‘t’. That means the current thread executing the code t.join() will not resume execution until thread ‘t’ completes.
Lets take a simple coding example to understand it better. Lets say we have three threads ONE, TWO and THREE and we want them to run in sequence i.e., THREE runs after TWO and TWO runs after ONE. So obviously we are going to join them one after another..but HOW?
Lets see HOW.
Our first Class is MyThread class which is our thread class.
package mishra.bagish; public class MyThread implements Runnable { private Thread thread; public MyThread(Thread t) { thread = t; } @Override public void run() { System.out.println(Thread.currentThread().getName()+" Going to join given thread"); if(thread!=null) { try{ thread.join(); } catch(InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+" START"); //do some code System.out.println(Thread.currentThread().getName()+" END"); } }
So in above class, we are having a reference to a thread for which the current thread is going to wait for. Actually when thread.start() run by jvm the run() method of the thread might get the cpu time any time and there is no fixed schedule. So what we have done is after printing first line we are calling join() to the join the current thread behind the thread referenced by ‘thread’. Once the thread ‘thread’ completes, the only the current comes backs to runnable state.
Now lets see a main code which has main() method and creates all threads and starts them.
package mishra.bagish; public class MainCasss { public static void main(String[] args) { Thread one = new Thread(new MyThread(null),"ONE"); Thread two = new Thread(new MyThread(one),"TWO"); Thread three = new Thread(new MyThread(two),"THREE"); one.start(); two.start(); three.start(); } }
So here we are starting three threads ONE, TWO and THREE. Each of them is passed with a reference of the thread which they are going to join or follow. Thread ONE is not given any reference since we want this thread to go first and rest to follow it. So in this example TWO will join with ONE and THREE will join with two.
Output
TWO Going to join given thread ONE Going to join given thread THREE Going to join given thread ONE START ONE END TWO START TWO END THREE START THREE END
Although TWO got scheduled first followed by ONE followed by THREE. Since we joined TWO with ONE so TWO suspends it execution till ONE completes. And THREE suspends its execution till TWO completes. No matter how may times we runs this code, the thread starting sequence might change but the sequence of
ONE START ONE END TWO START TWO END THREE START THREE END
will never change.