如何捕获线程异常

  1. 方法一:重写线程工厂,重写afterExecute 方法
  2. 方法二:设置一个全局异常处理器
public class MyWork {

    public static void main(String[] args) {

        ThreadPoolExecutor executor=
                new ThreadPoolExecutor(
                        1,
                        1,
                        0,
                        TimeUnit.HOURS,
                        new LinkedBlockingDeque<>(3)
                ){

                    @Override
                    protected void afterExecute(Runnable r, Throwable t) {
                        System.err.printf("线程[%s] 遇到异常",Thread.currentThread().getName()
                        ,t.getMessage());
                    }
                };
        executor.execute(
                ()->{
                    Thread.currentThread().setName("老弟线程");
                    throw new RuntimeException("抱歉,看你不顺眼");
                }
        );
        try {
            executor.awaitTermination(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            executor.shutdown();
        }






    }



    
}
public class MyWork {

    public static void main(String[] args) {
        //设置一个全局的异常处理器
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread t, Throwable e) {
                //用系统异常输出流输出类似日志的信息(其实就是模拟日志),格式是 时间戳 线程名称 异常名称 异常信息
                //这里在实际开发的时候要记得把异常堆栈也打印出来,这样便于排查问题
                System.err.println(String.format("%d %s %s",System.currentTimeMillis(),t.getName(),e.toString()));
            }

        });
        //通过for循环启动多个线程
        Thread tmp = new Thread(()->{
            System.out.println('-');
            int i = 0;
            int j = 10/i;
        });
        tmp.setName("老弟线程");
        tmp.start();




    }




}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值