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?
If your goal is simply to have 100 threads actively processing, I suggest looking at Java thread pools (and Executors more generally).
I'm unclear as to whether you want to keep all 100 threads going or wait for them all to finish. Your question references both (ThreadsWorker spawning 28 new threads, threadsCount==0) and they seem contradictory.
Put all the threads into an array or collection.
Then loop through the collection calling Thread.join() on each. When this loop completes, all threads are done.
ArrayList threads = new ArrayList();
for (int i = 0; i < 5; i++) {
Thread t = new AweseomeThread();
t.start();
threads.add(t);
}
for (Thread t : threads) {
t.join();
}
You'll need some exception handling too (such as InterruptedException). But, I'll leave that as an exercise for the reader... :)
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