Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine if child threads have completed

I am using multiple threads in my application using while(true) loop and now i want to exit from loop when all the active threads complete their work.

like image 815
Muhammad Waqas Avatar asked Mar 08 '10 05:03

Muhammad Waqas


People also ask

How do you know when a thread is finished?

Check Thread. isAlive() in a polling fashion -- generally discouraged -- to wait until each Thread has completed, or. Unorthodox, for each Thread in question, call setUncaughtExceptionHandler to call a method in your object, and program each Thread to throw an uncaught Exception when it completes, or.

Which is the best method that assures the completion of main thread after all child threads finishes their execution?

CountDownLatch is better option.

Which method makes the parent thread to wait for the child thread to complete?

In java Thread join method is used, so that main or parent thread can wait for its child thread to finish its execution and die.


1 Answers

Assuming that you have a list of the threads themselves, here are two approaches.

Solution the first:

Use Thread.Join() with a timespan parameter to synch up with each thread in turn. The return value tells you whether the thread has finished or not.

Solution the second:

Check Thread.IsAlive() to see if the thread is still running.

In either situation, make sure that your main thread yields processor time to the running threads, else your wait loop will consume most/all the CPU and starve your worker threads.

like image 126
Bevan Avatar answered Sep 24 '22 02:09

Bevan