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");   } } ExecutorService must be shutdown explicitly to reclaim the resources (CPU & Memory) occupied by threads which have already finished their job but still exist.
The ThreadPoolExecutor in Python provides a thread pool that lets you run tasks concurrently. You can add tasks to the pool by calling submit() with your function name, which will return a Future object. You can call the cancel() function on the Future object to cancel the task before it has started running.
You should loop on 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."); } If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With