Example program of join method in java

Here in this context, we are going to learn an example program of join method in Java.

Java is a language which provides built-in support for multithreaded programming.
Multithread programming means one or more process can run simultaneously for that we have assign thread for each process. Each thread represent a part of a program or process there is the main thread it means whenever we run a program a thread is initialized every time.
for initialization of new thread, there is method Thread().
join(): This method is of thread instance which is used to join the start of one thread’s execution to end of other thread’s execution such that a thread does not start running until another thread ends.
If join() is called on a Thread instance, the currently running processes thread will be blocked till the thread instance completes its execution

Java example program to show join() method

public class joinExample extends Thread
{  
 void executeAndWait()
{  
  for(int i=1;i<=4;i++){  
  
    Thread.sleep(100);  
   
  System.out.println(i);  
  }  
 }  
public static void main(String args[])
{  
 joinExample process1=new joinExample();  
 joinExample process2=new joinExample();   
 joinExample process3=new joinExample(); 
 joinExample process4=new joinExample(); 
 process1.start();  
 process1.join();  
 process2.join();
 process3.start();  
 process4.start();
 }  
}

Output:

       1
       2
       3
       1
       2
       3
       1
       1
       2
       2
       3
       3

Explanation of join method in Java

In this code, we initialize a class name joinExample in which we inherit all the function of Threads class by writing extends keyword.
We have created a method in which each process will run i number of times and will wait for 100millisecond after using the resources.
So here we notice that if we write process1.join() it will first complete it fully and then execute the other process.

So then we have provided resources to process2 so till it completely finishes process3 and process4 have to wait. After completion of process2, process3 and process4 will be executed simultaneously.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *