title: How to wait for a ThreadPoolExecutor to finish
body: <p><strong>My Question:</strong> How to execute a bunch of threaded objects on a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html"><code>ThreadPoolExecutor</code></a> and wait for them all to finish before moving on?</p>
  
  <p>I'm new to ThreadPoolExecutor. So this code is a test to learn how it works. Right now I don't even fill the <code>BlockingQueue</code> with the objects because I don't understand how to start the queue without calling <code>execute()</code> with another <code>RunnableObject</code>. Anyway, right now I just call <code>awaitTermination()</code> but I think I'm still missing something. Any tips would be great! Thanks.</p>
  
  <pre><code>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 &lt; limit; i++) {
      ex.execute(new RunnableObject(i + 1));
    }
    ex.awaitTermination(2, TimeUnit.SECONDS);
    System.out.println("finished");
  }
  </code></pre>
  
  <p>The RunnableObject class:</p>
  
  <pre><code>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");
    }
  }
  </code></pre>