Wait for all threads to complete execution in java?

When you create threads keep all thread objects in Array in main method. After that apply Thread.join() method in loop. Like below example, it will not stop threads execution but will wait in main method for completion of all threads. Refer below example or copy it and add your logic as you need.

import java.util.ArrayList;

public class MythreadTest {
    
    private static ArrayList<Thread> arrThreads = new ArrayList<Thread>();
    
    public static void main(String[] args) {
        try {
            for (int i = 0; i < 10; i++) 
            {
                Thread T1 = new Thread(new ThreadTest(i));                
                T1.start();                
                arrThreads.add(T1);
            } 
            
            for (int i = 0; i < arrThreads.size(); i++) 
            {
                arrThreads.get(i).join(); 
            } 
            //This for loop will not stop execution of any thread, 
            //only it will come out when all thread are executed    
            
            System.out.println("Main thread exiting ");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
class ThreadTest implements Runnable {
     private int i;
     ThreadTest(int ind) 
     {
        i = ind;
     }
     public void run() {
        try
        {
            System.out.println("Thread is started " + i);
            Thread.sleep(1000);
            System.out.println("Thread is exiting " + i);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
     }
}

Output:-

Thread is started 1
Thread is started 2
Thread is started 0
Thread is started 3
Thread is started 4
Thread is started 5
Thread is started 6
Thread is started 7
Thread is started 9
Thread is started 8
Thread is exiting 2
Thread is exiting 0
Thread is exiting 1
Thread is exiting 3
Thread is exiting 5
Thread is exiting 4
Thread is exiting 6
Thread is exiting 7
Thread is exiting 8
Thread is exiting 9
Main thread exiting

11,710 total views, 4 views today

Wait for all threads to finish java
Tagged on:         

Leave a Reply to Anonymous Cancel reply

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