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

2022-09-01 20:03:09

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

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

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

}

谢谢你的帮助家伙!

埃里克


答案 1

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

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

答案 2

您可以在 s 和主线程之间共享一个对象,并在线程完成任务后立即调用这些线程。使用线程数加 1(对于主线程)构造屏障。主线程将在所有 s 完成后继续。查看 http://java.sun.com/javase/6/docs/api/java/util/concurrent/CyclicBarrier.htmlCyclicBarrierRaceCarRaceCarawait()RaceCarRaceCar

详细地说,在主线程中构造 a,并在方法退出之前在类中添加一个调用,并在主线程中的调用之前添加一个调用。CyclicBarrierbarrier.await()RaceCarrun()barrier.await()System.out.println()