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.
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.
CountDownLatch is better option.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With