在 Java 中等待多个线程完成 [英] Waiting on multiple threads to complete in Java

查看:24
本文介绍了在 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屋!

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