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!");
}
謝謝你的幫助!
埃里克
總結
以上是生活随笔為你收集整理的java线程死亡_java – 如何暂停main()直到所有其他线程死亡?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos7开发java体验_cent
- 下一篇: Twipstopixels java_1