multithreading - How to Count the number of threads completed in java without polling for the threads status -
in java program, have start n number of threads, , each thread performs operation . these threads continue operating in parallel. have monitor, number of threads have completed operation , mark progress of operation in percentage.
the method, think of poll through entire thread array , keep checking status, unless nodes have completed execution. however, wastage of cpu, other possible way achieve this?
easy. have each thread (or each thread's runnable
) increment shared atomicinteger
instance when completes.
other alternatives include:
- using
semaphore
orcountdownlatch
- using callback; e.g. using events , event listener
- using
wait()
,notify()
.
but careful. if using counter determine if threads have finished need deal case thread dies due uncaught exception. can using uncaught exception handler.
Comments
Post a Comment