Runtime. GetRuntime () through Runtime void Addshutdownhook
(thread hook) registers a shutdown hook event with the Java Virtual machine so that once the program end event arrives, the thread hook is run and we should actually
In time, just do some of the work done before the program needs to be done directly through the thread hook.
Example 1:
/*****************************************************************************
This program only demonstrates how to add a system exit event handling mechanism to a Java application
*****************************************************************************/
Package UNTITLED14;
Import java.util.*;
Import java.io.*;
/**
* This application are used to demo how to hook the event of a application
*/
public class Untitled1 {
Public Untitled1 () {
Doshutdownwork ();
}
/***************************************************************************
* the right Work that'll do before the system shutdown
* Here for demonstration, added an event handler for the application's exit
* When the application exits, the program The date of the exit is written to the D:/t.log file
**************************************************************************/
private void Doshutdownwork () {
Runtime . GetRuntime (). Addshutdownhook (New Thread () {
public void Run () {
try {
FileWriter FW = new FileWriter ("D://t.log");
System.out.println ("I ' m going to end");
Fw.write ("The Application ended!" + (new Date ()). ToString ());
Fw.close ();
}
catch (IOException ex) {
}
}
});
}
In the above program, we can see that by adding Runtime. GetRuntime (). Addshutdownhook (New Thread ()) event monitoring in the program, capturing the system
Exit messages come in, and then execute what we need to do to get the work done so that our programs are more robust.
Example 2:
/**
wangjianqing2017-06-01
@modifier* *public class
Test1 {public
static void Main (string[] args) {
Classpathxmlapplicationcontext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Runtime.getruntime (). Addshutdownhook (New Thread (Context::close));
Context.start ();
System.exit (0);
}
}
The above program closes the context after reading the configuration file. Context::close is a jdk8 syntax, instead of an anonymous class.