1. Application Application inject custom hook program
The Java language itself provides a good runtime class that allows us to get run-time information very well. One of the methods is the public void Addshutdownhook (thread hook), which allows us to get the main thread or the application item that was killed by kill to get the hook event when the exception exits. We usually deal with the release of resources, notifications, alarms and other information in this event, so that we can not turn log logs.
Note: For kill-9 such a violent end to the application does not work, so the general server to stop the running service is very taboo to use the kill-9 command to operate;
The specific implementation code is as follows:
public class Applicationhook {public static void Main (string[] args) { runtime.getruntime (). Addshutdownhook ( New Thread (()->{ System.out.println (Thread.CurrentThread (). GetName () + "This application would close ..."); , "Thread-su-hook")); New Thread (()->{ do{ System.out.println (Thread.CurrentThread (). GetName () + "is working ..."); try { thread.sleep (1000L); } catch (Interruptedexception e) { e.printstacktrace ()} } while (true); }, "thread-su-0"). Start (); }}
Output Result:
2, Thread thread exception throw is generally in the Run method internal digestion, but for runtime exception, thread thread seems powerless, So the thread class itself provides a way to implement capturing Setuncaughtexceptionhandler for special runtime errors;
The specific code is as follows:
public class Threadhook {public static void main (string[] args) {final int a = 100; Final int b = 0; Thread t = new Thread (()->{int count = 0; Optional.of (Thread.CurrentThread (). GetName () + "is begin work ..."). Ifpresent (System.out::p rintln); do{count++; Optional.of (Thread.CurrentThread (). GetName () + "count is:" + count). Ifpresent (System.out::p rintln); try {thread.sleep (1000L); } catch (Interruptedexception e) {e.printstacktrace (); }}while (count<5); Optional.of (Thread.CurrentThread (). GetName () + "is end work ..."). Ifpresent (System.out::p rintln); System.out.println (A/b); }); T.setuncaughtexceptionhandler ((thread,e)->{System.out.println (thread.getname () + "is custom uncaught excep tion ... "); }); T.start (); }
Input Result:
Hope to help the needs of friends, thank you ...
Capture method for application exception exits and thread exception crashes in the Java language, and exception handling in captured hook methods