如何暂停main()直到所有其他线程都死掉?

eri*_*cso 23 java multithreading

在我的程序中,我在main()方法中创建了几个线程.main方法的最后一行是对System.out.println()的调用,在所有线程都死之前我不想调用它.我已经尝试在每个线程上调用Thread.join()但是阻塞每个线程以便它们顺序执行而不是并行执行.

有没有办法阻止main()线程,直到所有其他线程完成执行?这是我的代码的相关部分:

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!");

}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

埃里克

mid*_*dus 46

您启动线程并立即等待它们完成(使用join()).相反,你应该join()在另一个for循环中执行for循环的外部,例如:

// start all threads
for(int i=0; i<numberOfRaceCars; i++) {
    racecars[i].start();
}
// threads run... we could yield explicity to allow the other threads to execute
// before we move on, all threads have to finish
for(int i=0; i<numberOfRaceCars; i++) {
    racecars[i].join(); // TODO Exception handling
}
// now we can print
System.out.println("It's over!");
Run Code Online (Sandbox Code Playgroud)

  • 这显然是正确的方法.我无法相信提倡使用wait()和notify()的其他答案以及障碍得到了支持:对于这种情况,它们太复杂了. (3认同)

the*_*ing 6

您可以CyclicBarrierRaceCars和主线程之间共享一个对象,并在完成任务后立即RaceCar调用线程await().使用RaceCar线程数加1(对于主线程)构造屏障.所有RaceCars完成后,主线程将继续.请参阅http://java.sun.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.html

详细地说,CyclicBarrier在主线程中构造一个,并在方法退出之前barrier.await()RaceCar类中run()添加一个barrier.await()调用,也在System.out.println()主线程中调用之前添加一个调用.