title: How can I make sure that all threads ended before the main thread ends?
body: <p>I have the following piece of code to employ java multi-threading.</p>
  
  <pre><code>    ExecutorService threadExecutor = Executors.newFixedThreadPool(10);
  
      while(resultSet.next()) 
         { 
            name=resultSet.getString("hName");
            MyRunnable worker = new  Myrunnable(name);
            threadExecutor.execute( worker );
            Counter++;
      }
  
  
   threadExecutor.shutdown();
   System.out.println("thread shutdown");
  
   // Wait until all threads are finish
   while (! threadExecutor.isTerminated()) {
  
   }
  
   System.out.println("Finished all threads");
  
  }// end try
      catch (Exception e) {
          e.printStackTrace();
      }
  
      System.out.println("END MAIN");
  
      DBConnection.con.close();           
  </code></pre>
  
  <p>And the run function as follows:</p>
  
  <pre><code>//The constructor
  MyRunnable (String name)  {
          this.name=name;
      }
  
  public void run() 
  {
          myclass Obj=new myclass();
          try {
              Obj.myFunction(name);
          } catch (Exception e) {
  
              System.out.println("Got an Exception: "+e.getMessage());
          }
          System.out.println(" thread exiting.");
  }
  </code></pre>
  
  <p>In a previous posts, somebody suggested the following code to wait for threads to end.</p>
  
  <pre><code>while (! threadExecutor.isTerminated()) {
     try {
         threadExecutor.awaitTermination(1, TimeUnit.SECOND);
     }
     catch (InterruptedException e) {
          // you have to determine if someone can interrupt your wait
          // for the full termination of the executor, but most likely,
          // you'll do nothing here and swallow the exception, or rethrow
          // it in a RuntimeException
     }
  }
  </code></pre>
  
  <p>Now, I'm facing problem in both cases. If I used the 1st method, my program runs but at the end it enters an infinite loop preceded by all threads exiting. The END MAIN print out never appears. If I used the 2nd method, I got the following error from the beginning of running the program, and also the END MAIN print out never appears:</p>
  
  <blockquote>
    <p>Got an Exception: No operations allowed after connection closed.
     thread exiting.</p>
  </blockquote>
  
  <p>Please, advise me in the correct way to make my Main thread exits after all my child threads exit.</p>