Android 线程池探究

在探究线程池之前,先说下线程池的优点,概括为以下三点:
(1) 重用线程池中的线程,避免因为线程的创建和销毁所带来的性能开销。
(2) 有效控制线程并发数,避免大量的线程抢占系统资源导致阻塞现象。
(3) 能对线程进行简单的管理,并提供定时执行以及指定间隔执行等功能。

Android中线程池的概念来源于Java中的Executor,Executor是一个接口,线程池的实现为ThreadPoolExecutor。ThreadPoolExecutor提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程池,从线程的功能特性上来说,Android的线程池主要分为4类,这4类线程池可以通过Exexutors所提供的工厂方法得到,具体会在下面介绍。由于Android中的线程池都是直接或者间接通过配置ThreadPoolExecutor来实现的,因此先介绍下ThreadPoolExecutor。

一、ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) 

corePoolSize
线程池核心线程数,默认情况下,核心线程会在线程池中一直存活,即使它们处于闲置状态。如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,那么闲置的核心线程在等待新任务到来时会有=超时策略,这个时间间隔由keepAliveTime指定,当等待时间超过keepAliveTime所指定的时长后,核心线程就会被终止。

maximumPoolSize
线程池能容纳最大线程数,当线程数达到这个值,后续任务将被阻塞。

keepAliveTime
非核心线程闲置的超时时长,超过这个时长,非核心线程将会被回收。当ThreadPoolExecutor的allowCoreThreadTimeOut为true时,keepAliveTime同样会作用域核心线程。

unit
keepAliveTime的时间单位。有TimeUnit .MILLISECONDS(毫秒)、TimeUnit .SECONDS(秒)以及分钟TimeUnit .MINUTES(分钟)等。

workQueue
任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中。

threadFactory
线程工厂,为线程提供创建新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable r)

handler
由于任务队列满了或者是无法成功执行任务,这时候ThreadPoolExecutor会通过调用handler的rejectedExecution方法来通知调用者,一般不常用,不作细讲。

ThreadPoolExecutor执行任务时有以下原则:
(1) 如果未达到核心线程的数量,那么会直接启动一个核心任务。
(2) 如果线程池中线程数量已经达到或者超过核心线程数量,那么任务将会被插入到任务队列中排队等待。
(3) 如果任务队列满了,这个时候线程数量还没达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务。
(4) 如果线程池达到了最大线程数,那么就拒绝执行任务,来调用RejectdExecutionHandler来通知调用者。

ThreadPoolExecutor的参数配置在AsyncTask中有明显的体现,下面是AsyncTask中线程池的配置情况:

	// 获取CPU数量
	private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    // 核心线程数定位2~4个
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    // 最大线程数为CPU数量*2+1
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    // 非核心线程的超时时间为30s
    private static final int KEEP_ALIVE_SECONDS = 30;
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };
	//任务队列的容量128
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);
            public static final Executor THREAD_POOL_EXECUTOR;

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

二、线程池的分类

通过直接的或者间接的配置ThreadPoolExecutor,可以将线程池分为FixedThreadPool、CachedThreadPool、ScheduledThreadPool和SingleThreadExecutor。

FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}

通过类Executors中的静态方法newFixedThreadPool创建。通过配置ThreadPoolExecutor的第一第二个参数,可以发现它是一种线程数量固定的线程池,所以当线程处于空闲状态时,它们并不会被回收,除非线程池关闭了。当所有的线程都处于活动状态时,新任务会处于等待状态,直到有线程空闲下来。由于FixedThreadPool只有核心线程并且这些线程不会被回收,这意味着它能够更加快速的响应外界的请求。另外有一点,从new LinkedBlockingQueue()中,我们发现任务队列是没有大小限制的。

CachedThreadPool

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}

从各项参数配置来看,它只有非核心线程,并且最大线程数是Integer.MAX_VALUE,可以理解为任意大,一旦有任务进来,就会创建一个新的非核心线程,线程处于闲置状态时,经过60s后会销毁。这里存储任务队列的类SynchronousQueue是跟FixedThreadPool中的LinkedBlockingQueue是不一样的,它是个非常特殊的队列,可以简单的理解为无法存储元素的队列。

ScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
}

它的核心线程数量是固定的,而非核心线程数是没有限制的,并且当非核心线程闲置时会被立即回收。这类线程主要用于执行定时任务和具有固定周期的重复任务。

SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}

这类型线程池内部只有一个核心线程,它确保所有的任务都在一个线程中按顺序执行。它的意义在于统一所有外界任务到一个线程中,这使得在这些任务之间不需要处理线程同步问题。

三、用法

Runnable command = new Runnable(){
	@override
	public void run(){
		SystemClock.sleep(2000);
	}
}

ExectorService fixedThreadPool = Exectors.newFixedThreadPool(4);
fixedThreadPool.execute(command);

ExectorService cacheThreadPool = Exectors.newCachedThreadPool();
cacheThreadPool.execute(command);

ScheduledExecutorService scheduledThreadPool = Exectors.newScheduledThreadPool(4);
//2s后执行command 
scheduledThreadPool.schedule(command, 2000, TimeUnit.MILLISECONDS);
//延迟10ms,每隔1s执行一次command
scheduledThreadPool.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);

ExectorService  singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(command);


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值