关于Android中常用的四种线程池的介绍

一,写在前面

       线程池的好处:可以在设定固定数量的线程池,并重用线程池中的线程,避免了线程不断的创建和销毁带来的性能开销。另外,还可以定时以及间隔循环执行任务。
      
       Android线程池有哪些:FixedThreadPool,SingleThreadPool,CacheThreadPool,ScheduledThreadPool。事实上,前面列出的四种线程池并不是类,是对线程池的描述。具体来说,FixedThreadPool是固定大小线程池,SingleThreadPool是单任务线程池,CacheThreadPool非固定大小线程池,ScheduledThreadPool是具有定时,间隔循环执行任务的线程池。
       
       什么是线程池?Android线程池是由Java提供的原生API支持,代表线程池的是一个接口Executor,它只有一个execute方法。有一些子类:ThreadPoolExecutor,AbstractExecutorService;有一些子接口:ScheduledExecutorService,ExecutorService。
       接口Executor真正实现类是ThreadPoolExecutor,上面提到的四种线程池实质都是ThreadPoolExecutor,只是创建ThreadPoolExecutor对象时传入的参数值不同。因此,研究常用四种线程池前需要认识ThreadPoolExecutor,下面会重点研究。

二,ThreadPoolExecutor分析

       查看接口Executor源码:
public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}
       第13行,定义了一个execute方法,子类ThreadPoolExecutor会重写该方法,参数command指被执行的任务。

       查看ThreadPoolExecutor构造方法,主要研究其参数,源码如下:
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler){
	//...code

}
        corePoolSize:核心线程的数量。核心线程在默认情况下,没有闲置状态的超时机制,不会被系统回收。如果调用ThreadPoolExecutor$allowCoreThreadTimeOut(true),设置属性allowCoreThreadTimeOut值为true,那么核心线程在闲置状态时有超时机制,可以被回收。
      
        maximumPoolSize:线程池中允许的线程最大数量;
       
       
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值