java线程死亡_java – 如何暂停main()直到所有其他线程死亡?
在我的程序中,我在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
racecars[i] = new RaceCar(laps, args[i]);
}
//Call start() on each Thread
for(int i=0; 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!");
}
谢谢你的帮助!
埃里克
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
