如何暂停main()直到所有其他线程都死掉? [英] How do I pause main() until all other threads have died?

查看:85
本文介绍了如何暂停main()直到所有其他线程都死掉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my program, I am creating several threads in the main() method. The last line in the main method is a call to System.out.println(), which I don't want to call until all the threads have died. I have tried calling Thread.join() on each thread however that blocks each thread so that they execute sequentially instead of in parallel.

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

Is there a way to block the main() thread until all other threads have finished executing? Here is the relevant part of my code:

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

}

感谢帮助人员!

Eric

推荐答案

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

You start your threads and immediately wait for them to be finished (using join()). Instead, you should do the join() outside of the for-loop in another for-loop, e.g.:

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

这篇关于如何暂停main()直到所有其他线程都死掉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆