content: In many real-world applications, when users close applications, they need to do some cleanup work. However, the problem is that users sometimes do not follow the recommended method of closing the program, and many may not do cleanup work. Closing the hook is a solution to ensure that the cleanup code is always executed, regardless of the user closing the application. We closed the hook by registering with the Runtime class: A thread that has been initialized but not yet started. When a virtual machine starts to enable its shutdown sequence, it starts all registered closed hooks in an unspecified order and lets them run concurrently.
public class Shutdownhookdemo {public void start () {System.out.println ("Demo"); Shutdownhook Shutdownhook = new Shutdownhook (); Runtime.getruntime (). Addshutdownhook (Shutdownhook);} Class Shutdownhook extends Thread {public void run () {System.out.println ("shutting down, then do something");}} public static void Main (string[] args) {Shutdownhookdemo demo = new Shutdownhookdemo ();d Emo.start (); try {//exit SYSTEM.IN.R EAD ();} catch (Exception e) {}}}
Application of Java Closure hooks