Java多线程——线程池异常捕获

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

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

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

可以看到:

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

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

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<Runnable> 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;
        @Override
        public 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

可以看到:

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

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

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

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

afterExecute

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

demo:

public class AfterExecuteException {
    public static void main(String[] args) {
        int corePoolSize = 3;
        int maxPoolSize = 5;
        long keepAliveTime = 10;
        BlockingDeque<Runnable> queue = new LinkedBlockingDeque<>(5);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, queue) {

            @Override
            protected 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;

        @Override
        public 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

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java线程编程中,配置线程池的参数是非常重要的。根据不同的业务需求,可以设置线程池的参数来控制线程的数量和行为。根据引用中的例子,可以使用`Executors.newFixedThreadPool(int nThreads)`来创建一个固定线程数量的线程池。在这个方法中,`nThreads`参数表示线程池中的线程数量,只有这个数量的线程会被创建。然后,可以使用`pool.execute(Runnable command)`方法来提交任务给线程池执行。 在配置线程池时,需要考虑业务的性质。如果是CPU密集型的任务,比如加密、计算hash等,最佳线程数一般为CPU核心数的1-2倍。而如果是IO密集型的任务,比如读写数据库、文件、网络读写等,最佳线程数一般会大于CPU核心数很多倍。这样可以充分利用IO等待时间来执行其他任务,提高程序的性能。引用中给出了一些常见的线程池特点和构造方法参数。 总之,根据业务需求和特点,合理配置线程池的参数可以提高程序的性能和效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java线程之线程池的参数和配置](https://blog.csdn.net/MRZHQ/article/details/129107342)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Java线程之线程池(合理分配资源)](https://blog.csdn.net/m0_52861000/article/details/126869155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Java线程之线程池](https://blog.csdn.net/weixin_53611788/article/details/129602719)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不能吃辣的JAVA程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值