ThreadPoolExecutor线程池异常被吞问题分析

一、起因:

在使用ScheduledThreadPoolExecutor执行一个定时任务时,发现执行一次后,任务就不再执行。
代码举例:

private static final ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);
 private static final CountDownLatch countDownLatch = 

public static void main(String[] args) throws InterruptedException {
   
        System.out.println("start");
        executorService.scheduleAtFixedRate(() -> {
   
            System.out.println("task");
                //test() 调用第三方接口
        }, 0, 2, TimeUnit.SECONDS);
//        executor();
        countDownLatch.await();
    }

代码走到调用第三方接口后,三方接口内日志只打印了部分,推测接口没有执行完就出错了,测试后发现第三方项目没有启动,连接超时,所以调用失败,但是为啥没有报错日志,异常日志被吞。

二、ScheduledThreadPoolExecutor源码分析
(1)ScheduledThreadPoolExecutor继承了ThreadPoolExecutor,先看scheduleAtFixedRate方法

1public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit) {
   
        if (command == null || unit == null)
            throw new NullPointerException();
        if (period <= 0)
            throw new IllegalArgumentException();
            //这里把我们传的Runnable封装成了一个FutureTask对象
        ScheduledFutureTask<Void> sft =
            new ScheduledFutureTask<Void>(command,
                                          null,
                                          triggerTime(initialDelay, unit),
                                          unit.toNanos(period));
        RunnableScheduledFuture<Void> t = decorateTask(command, sft);
        sft.outerTask = t;
        delayedExecute(t);
        return t;
    }
2ScheduledFutureTask(Runnable r, V result, long ns, long period) {
   
            super(r, result);
            this.time = ns;
            this.period = period;
            this.sequenceNumber = sequencer.getAndIncrement();
        }
        //在进入 super(r, result);
 
public FutureTask(Runnable runnable, V result) {
   
        this.callable = Executors.callable(runnable, result);
        this
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值