# Java实战系列 - 线程池中的线程出现异常

问题:线程池中的线程执行任务出现异常,该线程接下来的命运如何?

结论:线程会结束,线程池会新建线程替换该线程

验证:编码验证,代码如下

public class ThreadPoolExceptionTest {

    // 创建一个核心线程数、最大线程数都为1的线程池,任务队列最大容量为10
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10),
            new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy());

    public static void main(String[] args) {

        executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 0)));
        try {
            // 睡眠1秒,让打印结果更明显
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 1)));
        executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 2)));
        executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 3)));
        executor.execute(() -> System.out.println(Thread.currentThread().getName() + " " + (1 / 4)));

    }
}
  • 打印日志如下:
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
    at com.lushwe.thread.ThreadPoolExceptionTest.lambda$main$0(ThreadPoolExceptionTest.java:25)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
pool-1-thread-2 1
pool-1-thread-2 0
pool-1-thread-2 0
pool-1-thread-2 0
  • 总结:通过日志线程的线程名称可知,线程执行任务出现异常,该线程会结束,线程池会创建新的线程替换该线程执行其他任务。

本文完。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值