How to Count the number of threads completed in java without polling for the threads status
In a Java program, I have to start n number of threads, and each thread performs an operation . All these threads continue operating in parallel. I have to monitor, the number of threads that ha开发者_开发百科ve completed their operation , so as to mark the progress of the operation in percentage.
The only method, I could think of is to poll through the entire thread array and keep checking their status, unless all the nodes have completed their execution. However, this is wastage of CPU, is their any other possible way to achieve this?
Easy. Have each thread (or each thread's Runnable
) increment a shared AtomicInteger
instance when it completes.
Other alternatives include:
- using a
Semaphore
or aCountdownLatch
- using a callback; e.g. using events and an event listener
- using
wait()
andnotify()
.
But be careful. If you are using this counter to determine if all threads have finished you also need to deal with the case where a thread dies due to an uncaught exception. You can do that using an uncaught exception handler.
You can increment global AtomicInteger
field just in the end of threads' run()
method.
You should read this article. It mentions several possibilities with its pro and cons, and ends up with the already mentioned AtomicInteger.
精彩评论