1

I'm quite new to multithreading and this is what I want to do:

How can I check if all my started threads have finished?

I start them by doing this

for (Auftrag auftrag: auftragsliste) {
  RunnableFS thread = new RunnableFS(auftrag, optionen, elmafs);
  thread.start();
}

// I want to do something here after all my above started threads have finished

I know that by thread.join() I could implement a point where the mainthread waits until the other one has finished. But if I do this in the for-loop I'm back to single threaded :(

bish
  • 3,381
  • 9
  • 48
  • 69
  • 2
    What is `RunnableFS`? –  Nov 01 '16 at 18:38
  • @LutzHorn `RunnableFS` is my class that implements `Runnable` – bish Nov 01 '16 at 19:02
  • @bish, why can't use ExecutorService? invokeAll() and iterating through all callable with Future.get() will achieve the purpose. Refer to this SE post: http://stackoverflow.com/questions/7939257/wait-until-all-threads-finish-their-work-in-java/36797569#36797569 – Ravindra babu Nov 01 '16 at 19:03
  • @Ravindrababu Thanks for the link and the documentation example in there. I'll have a look tomorrow! – bish Nov 01 '16 at 19:04

2 Answers2

3

You can maintain a list of RunnableFSs, after starting all the threads, you can loop through them and do join() (btw i dont know what is RunnableFS)

List<RunnableFS> threads = new ArrayList<>();

for (Auftrag auftrag: auftragsliste) {
   RunnableFS thread = new RunnableFS(auftrag, optionen, elmafs);
   thread.start();
   threads.add(thread);
}

// Later
for(RunnableFS thread: threads){
   thread.join();
}
Jos
  • 2,015
  • 1
  • 17
  • 22
2

CountDownLatch or CyclicBarrier from java.util.concurrent package are other alternatives to achieve similar use-cases.

Bhavesh
  • 519
  • 6
  • 26