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

來源:互聯網
上載者:User

標籤: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異常退出和線程異常崩潰的捕獲方法,並且在捕獲的鉤子方法中進行異常處理

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.