The Java shutdown hook is not running
I'm new to Java / threads, and I inherit code similar to the following It is a command line program. Main() only starts 5-6 different types of threads and exits with ^ C I want to add a close hook to close all threads correctly and adjust it as follows
I added a shutdown hook and a stopthread () method to all threads (such as the one in the myworker class)
The problem is that when I press ^ C, I don't see the end message in the run method of thread Is this done in the background or is there a problem with my method Besides, should I follow a better pattern?
thank you
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 } }
Solution
When you call system When exit () or signaled, it stops all existing threads and starts all close hooks That is, when you hook up, all your threads may be dead
You should ensure that the resource is completely shut down, rather than trying to stop the thread cleanly