1、application應用程序注入自定義鈎子程序
java語言本身提供一個很好的Runtime類,可以使我們很好的獲取運行時信息。其中有一個方法是 public void addShutdownHook(Thread hook) ,通過這個方法我們可以獲取主線程或者說application項目被kill殺死獲取異常退出時候的鈎子事件。我們一般會在這個事件中處理一些釋放資源,通知,報警等信息,這樣我們就可以不用翻log日志了。
注意:對於kill -9 這樣暴力結束應用程序的方式不起作用,所以一般服務器上停止正在運行的服務很忌諱使用kill -9 命令進行操作;
具體實現代碼如下:
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(); } }
輸出結果:
2、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(); }
輸入結果:
希望能幫到需要的朋友,謝謝。。。