zoukankan      html  css  js  c++  java
  • 解决主线程无法捕获其他线程异常信息思路

    Thread.UncaughtExceptionHandler 是JAVASE5的一个新接口,它允许每一个线程对象上附着一个异常处理器<br>

    Thread.UncaughtExceptionHandler.uncaughtException会在线程因未捕获的异常而濒临死亡时被调用

    public class ExceptionThread implements Runnable {
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Thread thread = Thread.currentThread();
            print("run by :" + thread);
            print("eh:" + thread.getUncaughtExceptionHandler());
            throw new RuntimeException();
    
        }
    
    }
    public class HandleThreadFactoryException implements ThreadFactory {
    
        @Override
        public Thread newThread(Runnable r) {
            // TODO Auto-generated method stub
            System.out.println(this + " create new Thread");
            Thread thread = new Thread(r);
            System.out.println("created:" + thread);
            thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandle());// 为当前线程设置一个自定义异常处理器
            System.out.println("eh:" + thread.getUncaughtExceptionHandler());
            return thread;
        }
    
    }
    /**
     自定义捕获器
     * 
     * @date:2018年6月28日
     * @author:zhangfs
     * 
     * 
     */
    public class MyUncaughtExceptionHandle implements Thread.UncaughtExceptionHandler {
    
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            // TODO Auto-generated method stub
            System.out.println("异常处理器打印异常:" + e);
    
        }
    
    }
        public static void main(String[] args) {
    
            ExecutorService executorService = Executors.newCachedThreadPool(new HandleThreadFactoryException());
            executorService.execute(new ExceptionThread());
            executorService.shutdown();
    
            // 默认异常捕获器
            /*
             * Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandle());
             * ExecutorService executorService = Executors.newCachedThreadPool();
             * executorService.execute(new ExceptionThread());
             * executorService.shutdown();
             */
    
        }
    
    }
    output:
    
    

    org.knowledge.muti.thread.caughtException.HandleThreadFactoryException@42a57993 create new Thread

    
    

    created:Thread[Thread-0,5,main]

    
    

    eh:org.knowledge.muti.thread.caughtException.MyUncaughtExceptionHandle@75b84c92

    
    

    run by :Thread[Thread-0,5,main]

    
    

    eh:org.knowledge.muti.thread.caughtException.MyUncaughtExceptionHandle@75b84c92

    
    

    异常处理器打印异常:java.lang.RuntimeException

     

     

  • 相关阅读:
    apache+mysql+php+phpmyadmin搭建
    Redis学习笔记(1)Redis安装和启动
    Zlib 引用中出现的问题
    约数
    AC自动机
    当我们说“一切皆对象”时,我们到底在说什么
    Google翻译,3个步骤灭绝人类
    Linux下Gcc生成和使用静态库和动态库详解(转)
    Java基础&笔试题
    SQL基础&笔试题
  • 原文地址:https://www.cnblogs.com/zhangfengshi/p/9239449.html
Copyright © 2011-2022 走看看