標籤:except 分享圖片 並且 ima ... print 好的 bsp rgs
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(); }
輸入結果:
希望能幫到需要的朋友,謝謝。。。
java語言中application異常退出和線程異常崩潰的捕獲方法,並且在捕獲的鉤子方法中進行異常處理