Android的线程池

2017-09-11  本文已影响27人  joker_fu

Android中的线程池来源于Java中的Executor接口,真正的线程池实现为ThreadPoolExecutor,它提供参数来配置线程池。既然提到线程池,首先得了解线程池有什么有点,线程池的优点主要有以下3点:

  1. 线程重用,通过重用线程池中线程避免反复创建和销毁县城带来的性能开销问题。
  2. 控制并发数,避免大量线程同时工作抢占系统资源造成阻塞。
  3. 简单的线程管理,实现定时执行等功能。

一 ThreadPoolExecutor

  1. ThreadPoolExecutor 构造器
     //使用给定的参数和默认线程工厂、拒绝执行的Handler创建一个新的ThreadPoolExecutor 
     ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
    
     //使用给定的参数和拒绝执行的Handler创建一个新的ThreadPoolExecutor。
     ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
     
     //使用给定的参数和默认线程工厂创建一个新的ThreadPoolExecutor
     ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler)

     //使用给定的参数创建一个新的ThreadPoolExecutor
     ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
 
  1. ThreadPoolExecutor 构造器参数说明
  1. ThreadPoolExecutor执行任务时大致规则
  1. ThreadPoolExecutor在AsyncTask中的使用
    private static final String LOG_TAG = "AsyncTask";

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

    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());
        }
    };

    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

通过源码,我们可以看到AsyncTask的THREAD_POOL_EXECUTOR属性配置如下:

以上对ThreadPoolExecutor和AsyncTask中的ThreadPoolExecutor配置进行了介绍。在Android中通过对ThreadPoolExecutor的配置实现了四类不同功能特性的线程池,接下来我们就对Android中的这四类线程池进行一个简单介绍

二 FixedThreadPool

通过Executors.newFixedThreadPool创建一个线程池,它使用固定数量的线程操作了共享无界队列。在任何时候,大多数线程都是主动处理任务的。如果在所有线程处于活动状态时提交其他任务,则它们将在队列中等待,直到有线程空闲可用为止。如果任何线程在关闭前在执行过程中失败,如果需要执行后续任务,则新线程将取代它。线程池中线程会一致存在,直到线程池明确关闭(shutdown)。下面是它的实现,可以看到它只有不会被回收的核心线程,队列大小也没有限制。

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

三 CachedThreadPool

通过Executors.newCachedThreadPool创建一个线程池,根据需要创建新线程,但在可用线程时将重用以前构建的线程。这些池通常会提高执行许多短期异步任务的程序的性能。如果先前创建线程可用的话,调用将重用先前构建的线程。如果没有现有的线程可用,一个新线程将被创建并添加到池。未使用六十秒的线程被终止并从缓存中移除。因此,空闲时间足够长的池不会消耗任何系统资源。下面是它的实现,可以看到与ThreadPoolExecutor不同的是它没有核心线程,最大线程数为Integer.MAX_VALUE,且CachedThreadPool的任务队列是一个SynchronousQueue的空集合,这将导致任务会被立即执行,所以这类线程比较适合执行大量耗时较少的任务。

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

四 ScheduledThreadPool

通过Executors.newScheduledThreadPoo创建一个线程池,可以在给定延迟后调度命令运行,或定期执行命令。它有数量固定的核心线程,且有数量无限多的非核心线程,但是它的非核心线程超时时间是0s,所以非核心线程一旦空闲立马就会被回收。这类线程池适合用于执行定时任务和固定周期的重复任务。

    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());
    }

五 newSingleThreadScheduledExecutor

通过Executors.newSingleThreadScheduledExecutor创建一个单线程执行器,可以在给定延迟后调度命令运行,或定期执行命令。任务是按顺序执行的,在任何给定的时间内都不会有一个任务处于活动状态,让调用者可以忽略线程同步问题。

    public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    }
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE,
              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
              new DelayedWorkQueue());
    }

六 线程池一般用法

除了上面4种线程池,还可以根据实际需求自定义线程池。

七 自定义线程池

ExecutorService mExecutor = Executors.newFixedThreadPool(5);

execute()方法,接收一个Runnable对象作为参数,异步执行。

Runnable myRunnable = new Runnable() {
    @Override
    public void run() {
        Log.i("myRunnable", "run");
    }
};
mExecutor.execute(myRunnable);
上一篇 下一篇

猜你喜欢

热点阅读