For example I need to always run 100 threads to do some action.
I have class which called ThreadsWorker
which looks for threads count and runs missing threads if some previous are finished.
So, this is the table which describes situation:
1 second: 100 threads
2 second: 92 threads (ThreadsWorker generates new 8 threads)
3 second: 100 theads
4 second: 72 threads (ThreadsWorker generates 28 threads)
And so on.
My threads are anonymous calls (just new Thread(new Runnable(...)).start()
) because I don't know how to correctly save them to Threads[]
array because, while ThreadsWorker
will save threads[i] = new Threads()
, some threads may be finished and then there will be some collision with array indexes.
Because of anonymous calls I use threadsCount
variable now and increment it in threads body beginning and decrements in threads body end (using synchronized
). Okay, it works correctly and my single way is to use while()
loop which checks if threadsCount == 0
when the progress is complete.
I think that this is C-style but not Java-way :) So, can you help me to do it in Java-way?