捕获异常_(九)线程池异常捕获

上一篇提到了使用ThreadFactory的UncaughtExceptionHandler去捕获线程池的错误,还有没有其他方法呢?

线程的异常捕获可以使用try catch,但是主线程 如何 捕获子线程的异常呢?当一个线程执行出错了,接下来是否还要执行呢?

1. try catch

在子线程执行的方法体里面加上 try catch ,try catch 可以捕获当前线程的抛出的异常。

但是try catch 无法捕获其他线程的错误。

demo:

public class OtherException {
    static class MyThread implements Runnable {

        @Override
        public void run() {
            throw new RuntimeException("子线程运行出错");
        }
    }

    public static void main(String[] args) throws Exception {
        Runnable runnable = new MyThread();
        try {
            for (int i = 0; i 3; i++) {
                Thread thread = new Thread(runnable);
                thread.start();
            }
        }catch (Exception e){
            throw new Exception("主线程捕获异常");
        }
    }
}

输出:

Exception in thread "Thread-1" java.lang.RuntimeException: 子线程运行出错
    at com.yudianxx.basic.线程.Executor.异常处理.OtherException$MyThread.run(OtherException.java:13)
    at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-2" java.lang.RuntimeException: 子线程运行出错
    at com.yudianxx.basic.线程.Executor.异常处理.OtherException$MyThread.run(OtherException.java:13)
    at java.lang.Thread.run(Thread.java:748)
Exception in thread "Thread-0" java.lang.RuntimeException: 子线程运行出错
    at com.yudianxx.basic.线程.Executor.异常处理.OtherException$MyThread.run(OtherException.java:13)
    at java.lang.Thread.run(Thread.java:748)

Process finished with exit code 0

可以看到:

  1. 主线程main 没有捕获到子线程的异常。

  2. 子线程抛出异常了,也没有try catch , 但是还是会继续执行。这是因为 start()方法是在主线程触发的。

2. ThreadFactory

ThreadFactory 可以自定义线程的名称、优先级、统一异常处理。

但是对于submit来说,异常会被Feture.get()方法抛出的异常覆盖。

核心是UncaughtExceptionHandler。

demo:

public class ThreadFactoryException {
    public static void main(String[] args) {
        int corePoolSize = 3;
        int maxPoolSize = 5;
        long keepAliveTime = 10;
        BlockingDeque queue = new LinkedBlockingDeque<>(5);
        ThreadFactory factory = (Runnable r) -> {
            Thread t = new Thread(r);
            t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
                System.out.println("factory的exceptionHandler捕捉到异常--->>> \n" + e.getMessage());
            });return t;
        };
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, queue, factory);
        runnable(executor);
    }static void runnable(ThreadPoolExecutor executor) {
        TestRunnable testRunnable = new TestRunnable();for (int i = 0; i 5; i++) {
            executor.execute(testRunnable);
        }
        executor.shutdown();
    }static class TestRunnable implements Runnable {private static volatile int i = 0;@Overridepublic void run() {
            i++;if (i == 2) {throw new RuntimeException("子线程异常,当前 i 的 值:" + i);
            } else {
                System.out.println(Thread.currentThread().getName() + " 子线程执行--->>> i 的值:" + i);
            }
        }
    }
}

输出:

Thread-0 子线程执行--->>> i 的值:2
Thread-3 子线程执行--->>> i 的值:4
Thread-0 子线程执行--->>> i 的值:5
factory的exceptionHandler捕捉到异常--->>> 子线程异常,当前 i 的 值:2
Thread-2 子线程执行--->>> i 的值:3

执行另一次输出:

Thread-0 子线程执行--->>> i 的值:1
Thread-2 子线程执行--->>> i 的值:3
Thread-2 子线程执行--->>> i 的值:5
Thread-0 子线程执行--->>> i 的值:4
factory的exceptionHandler捕捉到异常--->>> 子线程异常,当前 i 的 值:2

可以看到:

  1. ThreadFactory可以捕获到execute执行抛出的错误,可以用来做全局异常处理。

  2. 线程的执行是毫无顺序的,而且 第一个输出,第一行:

    Thread-0 子线程执行--->>> i 的值:2

    这个 i 输出的值竟然是 2,而不是 1,这个问题留到下一篇文章讲,涉及锁的问题。

3. afterExecute

afterExecute方法是捕获FutureTask抛出的异常。submit方法提交的任务可以使用这个方法捕获异常。

demo:

public class AfterExecuteException {
    public static void main(String[] args) {
        int corePoolSize = 3;
        int maxPoolSize = 5;
        long keepAliveTime = 10;
        BlockingDeque queue = new LinkedBlockingDeque<>(5);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, queue) {@Overrideprotected void afterExecute(Runnable r, Throwable t) {super.afterExecute(r, t);if (r instanceof FutureTask>) {try {
                        ((FutureTask>) r).get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    } catch (ExecutionException e) {
                        System.out.println("afterExecute 捕获到线程的异常返回值" + e.getMessage());
                    }
                }
            }
        };
        runnable(executor);
    }static void runnable(ThreadPoolExecutor executor) {
        TestRunnable testRunnable = new TestRunnable();for (int i = 0; i 5; i++) {
            executor.submit(testRunnable); //submit方法提交//     executor.execute(testRunnable); //execute方法提交异常只会直接抛出异常
        }
        executor.shutdown();
    }static class TestRunnable implements Runnable {private static volatile int i = 0;@Overridepublic void run() {
            i++;if (i == 2) {throw new RuntimeException("子线程异常,当前 i 的 值:" + i);
            } else {
                System.out.println(Thread.currentThread().getName() + " 子线程执行--->>> i 的值:" + i);
            }
        }
    }
}

输出:

pool-1-thread-1 子线程执行--->>> i 的值:1
afterExecute 捕获到线程的异常返回值java.lang.RuntimeException: 子线程异常,当前 i 的 值:2
pool-1-thread-1 子线程执行--->>> i 的值:3
pool-1-thread-2 子线程执行--->>> i 的值:4
pool-1-thread-3 子线程执行--->>> i 的值:5

参考:

Java多线程:捕获线程异常:

https://mp.weixin.qq.com/s/kl84A4W1W2iTJNylbfouFQ

--end--

71487895793d86195f888cca239aaba0.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值