gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:31:37 33 4
gpt4 key购买 nike

在我的程序中,我在 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!");

}

感谢大家的帮助!

埃里克

最佳答案

您启动线程并立即等待它们完成(使用 join())。相反,您应该在另一个 for 循环中的 for 循环之外执行 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!");

关于java - 如何暂停 main() 直到所有其他线程都死了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2436142/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com