title: Adding Thread in ThreadPool in Executor Service
body: <p>I am working on a Multithreading Program in which I am trying to make sure each Thread is running for <code>30 minutes</code>. Suppose if we have <code>10 threads</code> then each thread out of <code>10</code> should run for <code>30 minutes</code>.</p>
  
  <p>Below is my code-</p>
  
  <pre><code>class ThreadTask implements Runnable {
      private final long endTime;
  
      public ThreadTask(long endTime) {
          this.endTime = endTime;
      }
  
      @Override
      public void run() {
  
          while (System.currentTimeMillis() &lt;= endTime) {
  
              // do something meaningful
  
          }   
      }
  }
  
  public class TestPool {
  
      public static void main(String[] args) {
  
          // create thread pool with given size
          ExecutorService service = Executors.newFixedThreadPool(1000); 
  
          long startTime = System.currentTimeMillis();
          long endTime = startTime + (30 * 60 * 1000);
  
          for (int i = 0; i &lt; threads; i++) {
              service.submit(new ThreadTask(endTime));
          }
  
          // wait for termination        
          service.shutdown();
          service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
      }
  }
  </code></pre>
  
  <p><strong>Now my question is-</strong></p>
  
  <p>Does the above code guarantee that each thread is starting at the same time and running for <code>30 minutes</code>? I am not sure <strong>how much time it takes to put the thread in Thread Pool</strong>. But it looks like it might be possible that some of the thread will start little bit late and they won't be running for exactly <code>30 minutes</code>, might be less than 30 minutes.</p>
  
  <blockquote>
    <p>I am looking for each thread should start at same time and they should
    run for exactly <code>30 minutes</code></p>
  </blockquote>