等待多个线程在Java中完成 [英] Waiting on multiple threads to complete in Java
问题描述
在程序执行过程中,会启动许多线程。线程数量取决于用户定义的设置,但它们都使用不同的变量执行相同的方法。
During the course of my program execution, a number of threads are started. The amount of threads varies depending on user defined settings, but they are all executing the same method with different variables.
在某些情况下,执行期间需要清理,这部分是停止所有线程,我不希望它们立即停止,我只是设置一个他们检查的变量来终止它们。问题是它可以在线程停止前最多1/2秒。但是,我需要确保在清理可以继续之前所有线程都已停止。清理是从另一个线程执行的,所以从技术上来说我需要这个线程来等待其他线程完成。
In some situations, a clean up is required mid execution, part of this is stopping all the threads, I don't want them to stop immediately though, I just set a variable that they check for that terminates them. The problem is that it can be up to 1/2 second before the thread stops. However, I need to be sure that all threads have stopped before the clean up can continues. The cleanup is executed from another thread so technically I need this thread to wait for the other threads to finish.
我想到了几种方法,但它们都是似乎过于复杂。我希望有一些方法可以等待一组线程完成。这样的事情是否存在?
I have thought of several ways of doing this, but they all seem to be overly complex. I was hoping there would be some method that can wait for a group of threads to complete. Does anything like this exist?
谢谢。
推荐答案
加入它们一个接一个:
for (Thread thread : threads) {
thread.join();
}
(你需要用做一些事情InterruptedException
,如果出现问题,您可能希望提供超时,但这是基本想法......)
(You'll need to do something with InterruptedException
, and you may well want to provide a time-out in case things go wrong, but that's the basic idea...)
这篇关于等待多个线程在Java中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!