My Question: How to execute a bunch of threaded objects on a ThreadPoolExecutor
and wait for them all to finish before moving on?
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");
}
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");
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…