问题描述
我将根据for循环中的用户输入创建多个线程.因此,我将无法为其指定名称.有没有一种方法可以等待所有人完成我的主线程?我希望他们能够完成for循环.我知道我需要使用联接,但是有许多线程,我将如何使用它?还是有另一种方法?会是这样的:
I will make many threads according to user input in a for loop. Therefore I won't be able to assign names for them. Is there a way to wait all of them to finish to move on with my main thread? I want them to be finished out of that for loop. I know I need to use a join but with many many threads, how will I use it? Or is there another way? It will be like this:
for(int i = 0; i<inputs.size(); i++)
new SimpleThread(parameters).start();
仅使用主线程继续,其他线程完成.
go on with only main thread, others finished.
我该怎么做?
推荐答案
将线程存储在List<Thread>
中,然后迭代该列表并使用thread.join()
Store the threads in a List<Thread>
, then iterate the list and use thread.join()
您也可以查看java.util.concurrent
辅助工具. CyclicBarrier
或CountDownLatch
(由其他人指出).
You can also take a look at java.util.concurrent
aids. CyclicBarrier
or CountDownLatch
(as indicated by others) for example.
这篇关于如何等待所有线程(可变数量的线程)完成与Main的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!