一、application应用程序注入自定义钩子程序java
java语言自己提供一个很好的Runtime类,能够使咱们很好的获取运行时信息。其中有一个方法是 public void addShutdownHook(Thread hook) ,经过这个方法咱们能够获取主线程或者说application项目被kill杀死获取异常退出时候的钩子事件。咱们通常会在这个事件中处理一些释放资源,通知,报警等信息,这样咱们就能够不用翻log日志了。服务器
注意:对于kill -9 这样暴力结束应用程序的方式不起做用,因此通常服务器上中止正在运行的服务很忌讳使用kill -9 命令进行操做;app
具体实现代码以下:this
public class ApplicationHook { public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread(()->{ System.out.println(Thread.currentThread().getName() + "this application will 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(); } }
输出结果:spa
二、Thread线程的异常抛出通常都是在run方法内部进行消化,可是对于runtime的异常,Thread线程显得无能为力,因此Thread类自己提供了一个方法来实现对于特殊的runtime错误进行捕获setUncaughtExceptionHandler ;线程
具体代码以下:日志
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::println); do{ count++; Optional.of(Thread.currentThread().getName() + " count is : " + count).ifPresent(System.out::println); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } }while (count<5); Optional.of(Thread.currentThread().getName() + " is end work...").ifPresent(System.out::println); System.out.println(a/b); }); t.setUncaughtExceptionHandler((thread,e)->{ System.out.println(thread.getName() + " is custom uncaught exception ..."); }); t.start(); }
输入结果:blog
但愿能帮到须要的朋友,谢谢。。。事件