java - unable to predict when all the threads have finished execution -
here 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"); (int = 0; < 100; i++) { thread t1 = new thread(tg1, runnable, + ""); t1.start(); system.out.println("thread group name: " + tg1.getname()); } while (tg1.isdestroyed()) { system.out.println("yes success"); } system.out.println("completed"); } }
while part of o/p
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 unable predict when thread group completing execution.even ,while loop checking whether thread group destroyed not working.even after printing completed threads executing.
a threadgroup not complete execution. if want wait threads finish, have collect them , wait of them:
list<thread> allthreads = new arraylist<>(); (int = 0; < 100; i++) { thread t1 = new thread(tg1, runnable, + ""); t1.start(); allthreads.add(t1); } allthreads.foreach(thread::join);
threadgroups exist longer threads contain, might want add new threads threadgroup after threads have finished. merely grouping threads, not controlling them.
Comments
Post a Comment