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));                
            for (int i = 0; i < arrThreads.size(); i++) 
            //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) {
class ThreadTest implements Runnable {
     private int i;
     ThreadTest(int ind) 
        i = ind;
     public void run() {
            System.out.println("Thread is started " + i);
            System.out.println("Thread is exiting " + i);
        catch (Exception e) {


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,999 total views, 12 views today

Wait for all threads to finish java
Tagged on:         

Leave a Reply

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