Waiting on multiple threads to complete in Java(在 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 中等待多个线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中等待多个线程完成
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01