A complete Java program has at least a starting point, an end point. The starting point can be a constructor, then we're going to use the Addshutdownhook function of the runtime class at the end point
a simple program to add actions that need to be performed before the end of the application, such as shutting down the network connection, shutting down the database, and so on.
However, for a more complex multi-threaded application, the thread running state is more complex. It is difficult for us to anticipate when the program will end. How to handle the work we do when the application end event arrives. This uses the Java event-handling mechanism to exit the application.
to get to the current application-related Run-time object, use the static function GetRuntime in the runtime class to return to the current runtime.
register a new virtual machine with the runtime Addshutdownhook function to close the hook.
The specific demo is as follows:
[Java] View plain copy package test; public class testshutdownhook { public testshutdownhook () { doshutdownwork (); } private void doshutdownwork () { runtime run=runtime.getruntime ()//current Java application-related Run-time objects. run.addshutdownhook (New thread () { // Register a new virtual machine to turn off hooks @Override public void run ( ) { //the operation at the end of the program &NBSP;&NBSP;&NBSP;&NBSP;&NBSP; system.out.println ("program End Call"); } &NBSP;&NBSP;&NBSP;&NBSP}); } public static void main (String[] args) { new testshutdownhook (); for ( int i = 0; i < 1000; i++) { // Add here you need to process code } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (i); } } } in the above program, we can see that by adding Runtime.getruntime (). Addshutdownhook (New Thread ()) event listening in the program, capturing the system exit message arrives, and then, Perform all the work we need to do to make our programs more robust.