如何等待ThreadPoolExecutor完成 [英] How to wait for a ThreadPoolExecutor to finish
问题描述
我的问题:如何在 ThreadPoolExecutor
并等待它们全部完成然后再继续?
My Question: How to execute a bunch of threaded objects on a ThreadPoolExecutor
and wait for them all to finish before moving on?
我是ThreadPoolExecutor的新手。所以这段代码是一个测试它是如何工作的测试。现在我甚至没有用对象填充 BlockingQueue
,因为我不知道如何在不调用 execute()的情况下启动队列
另一个 RunnableObject
。无论如何,现在我只是打电话给 awaitTermination()
,但我想我还在遗漏一些东西。任何提示都会很棒!谢谢。
I'm new to ThreadPoolExecutor. So this code is a test to learn how it works. Right now I don't even fill the BlockingQueue
with the objects because I don't understand how to start the queue without calling execute()
with another RunnableObject
. Anyway, right now I just call awaitTermination()
but I think I'm still missing something. Any tips would be great! Thanks.
public void testThreadPoolExecutor() throws InterruptedException {
int limit = 20;
BlockingQueue q = new ArrayBlockingQueue(limit);
ThreadPoolExecutor ex = new ThreadPoolExecutor(limit, limit, 20, TimeUnit.SECONDS, q);
for (int i = 0; i < limit; i++) {
ex.execute(new RunnableObject(i + 1));
}
ex.awaitTermination(2, TimeUnit.SECONDS);
System.out.println("finished");
}
RunnableObject类:
The RunnableObject class:
package playground;
public class RunnableObject implements Runnable {
private final int id;
public RunnableObject(int id) {
this.id = id;
}
@Override
public void run() {
System.out.println("ID: " + id + " started");
try {
Thread.sleep(2354);
} catch (InterruptedException ignore) {
}
System.out.println("ID: " + id + " ended");
}
}
推荐答案
你应循环 awaitTermination
ExecutorService threads;
// ...
// Tell threads to finish off.
threads.shutdown();
// Wait for everything to finish.
while (!threads.awaitTermination(10, TimeUnit.SECONDS)) {
log.info("Awaiting completion of threads.");
}
这篇关于如何等待ThreadPoolExecutor完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!