title: Java Shutdown hook not run
body: <p>I am new to Java/threads and I inherited something like the following code. It is a command line program that main() only starts 5-6 different kind of threads and exits with ^C. I want to add a shutdown hook to close all threads properly and adapted it the following way. </p>
  
  <p>I added a Shutdown hook and a stopThread() method in all threads (like the one in MyWorker class)</p>
  
  <p>The problem is that when I press ^C I don't see the end message from the Thread's run method. Is this done in the background or is there something wrong with my method. Also, Is there a better pattern I should follow?</p>
  
  <p>Thanks</p>
  
  <pre><code> public class Main {
       public static MyWorker worker1 = new MyWorker();
       // .. various other threads here
  
       public static void startThreads() {
           worker1.start();
           // .. start other threads
       }
  
       public static void stopThreads() {
           worker1.stopThread();
           // .. stop other threads
       }
  
       public static void main(String[] args)
               throws Exception {
  
           startThreads();
  
           // TODO this needs more work (later)
  
           Runtime.getRuntime().addShutdownHook(new Thread() {
               @Override
               public void run() {
                   try {
                       stopThreads();
                   } catch (Exception exp) {
  
                   }
               }
           });
       } }
  
   public class MyWorker extends Thread {
       private volatile boolean stop = false;
  
       public void stopThread() {
           stop = true;
       }
  
       public void run() {
           while (!stop) {
               // Do stuff here
           }
           // Print exit message with logger
       } 
  }
  </code></pre>