title: Executor service -- not to block main program
body: <p>I am using <code>ExecutorService</code> and its blocking the main program for some time but I don't want to block the main program.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>public class Test {
  
      public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
          ExecutorService executor = null;
  
          try {
              executor = Executors.newFixedThreadPool(1);
  
              System.out.println("Start 1");
              Runnable task = new Runnable() {
                  public void run() {
                      System.out.println("Start 2");
                      try {
                          Thread.sleep(7000);
                          System.out.println("Start 5");
  
                      } catch (Exception e) {
  
                      }
                  }
              };
              System.out.println("Start 3");
  
              // executor.execute(task);
              Future future = executor.submit(task);
              Object result = future.get(9, TimeUnit.SECONDS);
              System.out.println("Start 4");
  
          } catch (Exception e) {
  
          } finally {
              System.out.println("finally");
              executor.shutdownNow();
          }
  
      }
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Start 1
  Start 3
  Start 2
  Start 5
  Start 4
  finally
  </code></pre>
  
  <p>Currently it does not print <code>Start 4</code> until and unless the thread completes the execution. What I am looking for is some mechanism where we can have a timeout and the thread runs in the background and does not block the main thread?</p>