Java Joining Thread
In the last chapter we have seen, how to use sleep() method in the threading.
Contents
Joining the Thread :
join() method Waits for the thread to die.
public final void join() throws InterruptedException
Method | join() |
---|---|
Use of Method | Waits for the thread to die. |
Throws Exception | InterruptedException |
Example #1 : Illustration of Java join method
package com.c4learn.thread; public class ThreadJoin extends Thread { public void run() { for (int i = 1; i < 5; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(e); } String threadName = Thread.currentThread().getName(); System.out.println(i + " # " + threadName ); } } public static void main(String[] args) throws InterruptedException { ThreadJoin t0 = new ThreadJoin(); ThreadJoin t1 = new ThreadJoin(); ThreadJoin t2 = new ThreadJoin(); t0.start(); t0.join(); t1.start(); t2.start(); } }
Output :
1 # Thread-0 2 # Thread-0 3 # Thread-0 4 # Thread-0 1 # Thread-1 1 # Thread-2 2 # Thread-1 2 # Thread-2 3 # Thread-1 3 # Thread-2 4 # Thread-1 4 # Thread-2
Explanation : join()
Seeing above program may create confusion about the exact working of the join method.
Following table will explain the different meaning of the join method.
Syntax | Meaning |
---|---|
t0.join() | t0.join() method is called to wait for the thread t0 to finish |
t0.join() | Alternate meaning - thread t0 says - "I want to finish first" |
t0.join() | Tells other thread to wait until thread t0 ends. |
t0.start(); t0.join(); t1.start(); t2.start();
Thus t1 & t2 thread will wait until the thread 0 finishes its execution. Thus in the output we can see first four rows as -
1 # Thread-0 2 # Thread-0 3 # Thread-0 4 # Thread-0
After finishing the t0 thread, t1 starts its execution.
Example #2 : Passing Time Parameter
package com.c4learn.thread; public class ThreadJoin extends Thread { public void run() { for (int i = 1; i < 5; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println(e); } String threadName = Thread.currentThread().getName(); System.out.println(i + " # " + threadName ); } } public static void main(String[] args) throws InterruptedException { ThreadJoin t0 = new ThreadJoin(); ThreadJoin t1 = new ThreadJoin(); ThreadJoin t2 = new ThreadJoin(); t0.start(); t0.join(1000); t1.start(); t2.start(); } }
Output :
1 # Thread-0 2 # Thread-0 1 # Thread-1 1 # Thread-2 3 # Thread-0 2 # Thread-1 2 # Thread-2 4 # Thread-0 3 # Thread-1 3 # Thread-2 4 # Thread-1 4 # Thread-2
Explanation :
In this case we have passed parameter to join method.
t0.join(1000);
Thread t0 completes its task for 1000 milliseconds (2 times in this case) then t1 and t2 starts executing.