by BehindJava

What is join method used for in MultiThreading Java

Home » java » What is join method used for in MultiThreading Java

In this tutorial we are going learn about join method in MultiThreading.

Thread.join()

  • The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait until the other thread to finish its execution.
  • Suppose th be the object the class Thread whose thread is doing its execution currently, then the c1.join(); statement ensures that th is finished before the program does the execution of the next statement.
  • When there are more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period.
  • However, similar to the sleep() method in Java, the join() method is also dependent on the operating system for the timing

    public class Counter extends Thread {
    
    private int threadNumber;
    
    public Counter(int threadNumber) {
    	this.threadNumber = threadNumber;
    }
    
    @Override
    public void run() {
    	for (int i = 0; i <= 5; i++) {
    		System.out.println(i + " Running Thread No:" + threadNumber);
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    
    public static void main(String args[]) {
    	for (int i = 0; i <= 5; i++) {
    		Counter c1 = new Counter(i);
    		c1.start();
    		try {
    			c1.join();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }

}

Output:
```json
0 Running Thread No:0
1 Running Thread No:0
2 Running Thread No:0
3 Running Thread No:0
4 Running Thread No:0
5 Running Thread No:0
0 Running Thread No:1
1 Running Thread No:1
2 Running Thread No:1
3 Running Thread No:1
4 Running Thread No:1
5 Running Thread No:1
0 Running Thread No:2
1 Running Thread No:2
2 Running Thread No:2
3 Running Thread No:2
4 Running Thread No:2
5 Running Thread No:2
0 Running Thread No:3
1 Running Thread No:3
2 Running Thread No:3
3 Running Thread No:3
4 Running Thread No:3
5 Running Thread No:3
0 Running Thread No:4
1 Running Thread No:4
2 Running Thread No:4
3 Running Thread No:4
4 Running Thread No:4
5 Running Thread No:4
0 Running Thread No:5
1 Running Thread No:5
2 Running Thread No:5
3 Running Thread No:5
4 Running Thread No:5
5 Running Thread No:5