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

10,537 total views, 5 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

    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

  • October 18, 2018 at 5:12 am

    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.


Leave a Reply to Aboutcookies.org Cancel reply

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