java线程死亡_java – 如何暂停main()直到所有其他线程死亡?
在我的程序中,我在main()方法中創(chuàng)建了幾個(gè)線程。 main方法的最后一行是調(diào)用System.out.println(),在所有的線程都死了之前我不想調(diào)用它。我已經(jīng)嘗試在每個(gè)線程上調(diào)用Thread.join(),但阻塞每個(gè)線程,以便它們順序執(zhí)行而不是并行執(zhí)行。
有沒有辦法阻止main()線程,直到所有其他線程完成執(zhí)行?以下是我的代碼的相關(guān)部分:
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!");
}
謝謝你的幫助!
埃里克
總結(jié)
以上是生活随笔為你收集整理的java线程死亡_java – 如何暂停main()直到所有其他线程死亡?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos7开发java体验_cent
- 下一篇: 宣酱七星多少钱一瓶?