Search code examples
javamultithreadingrunnable

How to make sure all the subclass threads exited ?


Having -

for (int i = 0; i<10 ; i++) {
            Runnable r = new Runnable(){...}
            new Thread(r).start();
        } 
// I want to continue here only after all the subclass threads before exited . 
...

How could I make sure all the subclass threads exited before I continue on after the for section ?

Does exist any solution besides keep all the Runnable's in a List<Runnable> and finally check its isAlive() for each element ?


Solution

  • How could I make sure all the subclass threads exited before I continue on after the for section ?

    I'd use the ExecutorService classes. See the Java tutorial on them. Something like:

    // create a thread pool with 10 workers
    ExecutorService threadPool = Executors.newFixedThreadPool(10);
    // or you can create an open-ended thread pool
    // ExecutorService threadPool = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
       threadPool.submit(new Runnable(){...});
    }
    // once we have submitted all jobs to the thread pool, it should be shutdown
    threadPool.shutdown();
    

    Then you can wait for them to finish with:

    threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    

    If you still want to do your own threads then typically you keep them around in a List and call join() on each one of them:

    List<Thread> threadList = new ArrayList<Thread>();
    for (int i = 0; i < 10; i++) {
       Thread thread = new Thread(new Runnable(){...});
       thread.start();
       threadList.add(thread);
    }
    // this waits for all of the threads to finish before continuing
    for (Thread thread : threadList) {
       thread.join();
    }