smith smith - 3 months ago 13
Java Question

unable to predict when all the threads have finished execution

Here is my code

package pe.entel.ftp;

public class Myclass implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
Myclass runnable = new Myclass();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");

for (int i = 0; i < 100; i++) {
Thread t1 = new Thread(tg1, runnable, i + "");
t1.start();
System.out.println("Thread Group Name: " + tg1.getName());

}
while (tg1.isDestroyed()) {
System.out.println("yes success");
}

System.out.println("completed");

}
}


while my part of o/p is

Thread Group Name: Parent ThreadGroup
Thread Group Name: Parent ThreadGroup
Thread Group Name: Parent ThreadGroup
Thread Group Name: Parent ThreadGroup
Thread Group Name: Parent ThreadGroup
completed
84
86
88
90
92
94
96
98
95
97
99


Here I am unable to predict when exactly thread group is completing execution.Even ,while loop for checking whether thread group is destroyed is also not working.Even after printing completed some threads are executing.

Answer

A ThreadGroup does not complete execution. If you want to wait for all threads to finish, you have to collect them and wait for all of them:

List<Thread> allThreads = new ArrayList<>();

for (int i = 0; i < 100; i++) {
  Thread t1 = new Thread(tg1, runnable, i + "");
        t1.start();
   allThreads.add(t1);  
}

allThreads.forEach(Thread::join);

ThreadGroups exist longer than the threads they contain, you might want to add new threads to a ThreadGroup after all the threads up to now have finished. They are merely grouping threads, not controlling them.