zookeep源码中使用Thread 捕获异常方法UncaughtExceptionHandler解析

小G今天看zookeep源码的时候发现一个Quorumpeer.startLeaderElection 选举,中有一个

 responder = new ResponderThread();
                responder.start();

其实就一个线程,其实这里有一个封装的方法写的不做
我用java代码模拟下大家更容易看明白

package com.company;
import java.lang.Thread.UncaughtExceptionHandler;
public class test {
    public static void main(String[] args) {
        try {
            test t = new test();
            t.theadMethod();
            System.out.println("main end");

        }catch (Exception e){
            e.printStackTrace();
        }


    }
    public void theadMethod() {

        Thead1 thread1=new  Thead1();
        thread1.start();
    }

     class Thead1 extends Thread{

      public Thead1() {
            super("测试");
            //自动对异常的捕获
          setUncaughtExceptionHandler(uncaughtExceptionHandler);
      }
        UncaughtExceptionHandler uncaughtExceptionHandler=new UncaughtExceptionHandler(){

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                System.out.println("捕获");
                System.out.println(e);
                System.out.println(t.getName());
            }
        };


        @Override
        public void run() {

            System.out.println("开始实现代码");
            int i= 1/0;
            System.out.println("end");



        }
    }



}

打印出来的结果为:

main end
开始实现代码
捕获
java.lang.ArithmeticException: / by zero
测试

如果在run里面不写uncaughtExceptionHandler的话就无法进行捕获,main因为线程无法捕获run里面的方法,这个是公用的一个写法,当然也可以在run里面try,不过那样需要每个run都需要写,我们这就在构造函数上写一个

public Thead1() {
            super("测试");
            //自动对异常的捕获
          setUncaughtExceptionHandler(uncaughtExceptionHandler);
      }

当然也可以直接在在new Thread直接写

 Thead1 thread1=new  Thead1();
        thread1.setUncaughtExceptionHandler(new UncaughtExceptionHandler(){

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                
            }
        });
        thread1.start();

Thread源码分析可以看出

    /**
     * Dispatch an uncaught exception to the handler. This method is
     * intended to be called only by the JVM.
     *  发送一个未捕获的异常这个方法是jvm 调用
     */
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

jvm出错后调用dispatchUncaughtException,然后dispatchUncaughtException 调用uncaughtEcceptionHandler,
小G理解到此结束,本来想看下jvm原理不过不容易解析希望大家多提意见,写出大家更深的理解一块学习

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值