java語言中application異常退出和線程異常崩潰的捕獲方法,並且在捕獲的鈎子方法中進行異常處理


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();



    }

  輸入結果:

 

 

希望能幫到需要的朋友,謝謝。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM