Android小知识-定时任务ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor是Android中实现定时任务的类,继承自ThreadPoolExecutor。它提供了创建线程池的构造函数,参数包括核心线程数、最大线程数、线程存活时间等。ScheduledThreadPoolExecutor使用DelayedWorkQueue作为任务队列,该队列基于二叉堆算法,优先执行延迟时间最短的任务。ScheduledFutureTask是其内部类,用于存储任务信息和调度参数。相比Timer,ScheduledThreadPoolExecutor更安全且支持多线程处理任务,避免长时间任务影响其他任务执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本平台的文章更新会有延迟,大家可以关注微信公众号-顾林海,包括年底前会更新kotlin由浅入深系列教程,目前计划在微信公众号进行首发,如果大家想获取最新教程,请关注微信公众号,谢谢!

ScheduledThreadPoolExecutor继承自ThreadPoolExecutor,而ThreadPoolExecutor是线程池的核心实现类,用来执行被提交的任务,ScheduledThreadPoolExecutor是一个实现定时任务的类,可以在给定的延迟后运行命令,或者定期执行命令。

ScheduledThreadPoolExecutor定义了四个构造函数,这四个构造函数如下:

/**
* @param corePoolSize 核心线程池的大小
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE,
            DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
            new DelayedWorkQueue());
}

/**
* @param corePoolSize  核心线程池的大小
* @param threadFactory 用于设置创建线程的工厂
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory) {
    super(corePoolSize, Integer.MAX_VALUE,
            DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
            new DelayedWorkQueue(), threadFactory);
}

/**
* @param corePoolSize 核心线程池的大小
* @param handler      饱和策略
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
                                   RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE,
            DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
            new DelayedWorkQueue(), handler);
}

/**
* @param corePoolSize  核心线程池的大小
* @param threadFactory 用于设置创建线程的工厂
* @param handler       饱和策略
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory,
                                   RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE,
            DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
            new DelayedWorkQueue(), threadFactory, handler);
}
复制代码

通过源码可以发现,ScheduledThreadPoolExecutor的构造器都是调用父类的构造器也就是ThreadPoolExecutor的构造器,以此来创建一个线程池。

ThreadPoolExecutor的构造器如下:

public ThreadPoolExecutor(int corePoolSize,
                          
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值