How do I pause main() until all other threads have died?

Posted by thechiman on Stack Overflow See other posts from Stack Overflow or by thechiman
Published on 2010-03-12T21:51:33Z Indexed on 2010/03/12 21:57 UTC
Read the original article Hit count: 140

Filed under:
|

In my program, I am creating several threads in the main() method. The last line in the main method is a call to System.out.println(), which I don't want to call until all the threads have died. I have tried calling Thread.join() on each thread however that blocks each thread so that they execute sequentially instead of in parallel.

Is there a way to block the main() thread until all other threads have finished executing? Here is the relevant part of my code:

public static void main(String[] args) {

//some other initialization code

//Make array of Thread objects
Thread[] racecars = new Thread[numberOfRaceCars];

//Fill array with RaceCar objects
for(int i=0; i<numberOfRaceCars; i++) {
    racecars[i] = new RaceCar(laps, args[i]);
}

//Call start() on each Thread
for(int i=0; i<numberOfRaceCars; i++) {
    racecars[i].start();
    try {
        racecars[i].join(); //This is where I tried to using join()
                            //It just blocks all other threads until the current                            
                            //thread finishes.
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
}

//This is the line I want to execute after all other Threads have finished
System.out.println("It's Over!");

}

Thanks for the help guys!

Eric

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading