multithreading - How do I wait for a set of threads to 'really' finish in java? -


i have group of threads in java want run several times (each time different set of parameters). second run start want wait first run finish. should accomplished thread.join() before second run, since threads run in infinite loop have stop them interrupt, interrupts blocking join:

i have thread run() method looks this:

try {       while(true) {           printsomeinfo();         if (...) {             thread.currentthread().getthreadgroup().interrupt();         }     }  } catch (interruptedexception e) {       thread.currentthread().getthreadgroup().interrupt();   } {       printstats(); } 

and main method invoking run method of thread:

system.out.println("new run:"); (i ...) {    //first run     mythread[i] = new mythread(someinfostring1);     mythread[i].start(); } try {     (i...) {         mythread[i].join();     } } catch (interruptedexception e) {     e.printstacktrace(); } system.out.println("new run:"); (i ...) {    //second run     mythread[i] = new mythread(someinfostring2);     mythread[i].start(); } try {     (i...) {         mythread[i].join();     } } catch (interruptedexception e) {     e.printstacktrace(); } 

my problem second run starts printing out info, without first run being finished printing out printstats() method in block. output looks this:

new run: info 1 info 1 ... info 1 new run: (here comes stack trace) info 2 info 2 stats 1    <- should happen before second "new run:" ... info 2 stats 2 

how can wait first set of threads finish? there maybe more selective way interrupt running threads?

the problem lies in repeated use of thread.currentthread().getthreadgroup().interrupt() interrupts all threads in threadgroup, including 1 called join.

if @ loop, catching interruptedexception, not recovering correctly. loop contained within try…catch block , hence forcibly terminated exception. since want call join on threads, must proceed loop, including 1 join call has been interrupted:

threads: (i...) { // loop on threads     for(;;) { // recover join on interruptedexception         try {             mythread[i].join();             continue threads; // after successful join         } catch (interruptedexception e) {} // call join again     } } 

generally, interrupting entire threadgroup, or dealing outdated concept of thread groups @ all, not proper software design. should rewrite software interrupt inteded threads only. or use concurrency framework, esp. executorservice provides ways submit groups of tasks , cancel or wait all.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -