我的问题:如何在 a 上执行一堆线程对象ThreadPoolExecutor
并等待它们全部完成后再继续?
我是 ThreadPoolExecutor 的新手。所以这段代码是一个测试来了解它是如何工作的。现在我什至没有BlockingQueue
用对象填充 ,因为我不明白如何在不调用execute()
另一个RunnableObject
. 无论如何,现在我只是打电话awaitTermination()
,但我想我仍然错过了一些东西。任何提示都会很棒!谢谢。
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 类:
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");
}
}