gpt4 book ai didi

java - 如何确保所有子类线程都退出?

转载 作者:行者123 更新时间:2023-12-01 23:21:34 25 4
gpt4 key购买 nike

有 -

for (int i = 0; i<10 ; i++) {
Runnable r = new Runnable(){...}
new Thread(r).start();
}
// I want to continue here only after all the subclass threads before exited .
...

如何确保所有子类线程都退出,然后再继续 for部分 ?

除了保留所有 Runnable 之外,是否存在任何解决方案位于 List<Runnable>最后检查其isAlive()对于每个元素?

最佳答案

How could I make sure all the subclass threads exited before I continue on after the for section ?

我会使用ExecutorService类。请参阅Java tutorial在他们。类似于:

// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
threadPool.submit(new Runnable(){...});
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();

然后你可以等待他们完成:

threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

如果您仍然想执行自己的线程,那么通常您将它们保存在 List 中,并对每个线程调用 join():

List<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable(){...});
thread.start();
threadList.add(thread);
}
// this waits for all of the threads to finish before continuing
for (Thread thread : threadList) {
thread.join();
}

关于java - 如何确保所有子类线程都退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20553802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com