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

10,170 total views, 9 views today

Wait for all threads to finish java
Tagged on:         

2 thoughts on “Wait for all threads to finish java

  • April 26, 2017 at 3:39 am
    Permalink

    I see you don’t monetize your blog. You can earn extra income,
    your niche is good for one method, just search in google:
    reselling online by Riggso

    Reply
  • October 18, 2018 at 5:12 am
    Permalink

    I blog quite often and I seriously appreciate your content.

    This article has really peaked my interest. I’m going to bookmark your blog
    and keep checking for new details about once a week. I subscribed to your
    RSS feed too.

    Reply

Leave a Reply

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