In some scenarios, we design the service to take into account when the application stopped/stopped to do some clean-up operations, such as: Shut down the thread, release the connection resources.
In the Java language, we can register hooks through the Runtime.getruntime (). Addshutdownhook () method to guarantee smooth exit of the program as follows:
Runtime.getruntime (). Addshutdownhook (New Thread (new Runnable () {
@Override public
void Run () {
SYSTEM.OUT.PRINTLN ("Hook Running");
})
;
After registering the hook thread, the program receives the exit signal and keeps the program running until the hook thread finishes, stopping and exiting all of the program's threads.
Import Java.util.concurrent.TimeUnit; /** * ${description} * * @author Ricky Fung * @create 2016-11-22 13:33 * * public class Shutdownhooktest {public
static void Main (string[] args {//start 5 threads to perform task for (int i=0;i<5;i++) {final int id = i; New Thread (New Runnable () {@Override public void run () {Sy
Stem.out.println ("Thread_" +id+ "Start ...");
try {TimeUnit.SECONDS.sleep (ID);
catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread_" +id+ "finish!");}).
Start (); Runtime.getruntime (). Addshutdownhook (New Thread (new Runnable () {@Override public void
Run () {System.out.println ("hook running ...");
}
})); }
}