Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run 100 threads in parallel and run missing threads if some previous are finished

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?

like image 387
Clark Avatar asked Dec 03 '22 09:12

Clark


2 Answers

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.

like image 149
Michael Brewer-Davis Avatar answered Dec 11 '22 12:12

Michael Brewer-Davis


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... :)

like image 28
squawknull Avatar answered Dec 11 '22 10:12

squawknull