Android线程池的使用

来源:互联网 发布:微软软件license模式 编辑:程序博客网 时间:2024/06/17 06:30

线程池,顾名思义就像是存放线程的池子一样的,我们需要使用线程时,就从这个池子里面去取线程使用,用完之后,线程又会放回这个池子里面,等待下次的线程调用。使用线程池有很多好处,首先线程池中的线程可以重复利用,可以减少线程创建和销毁的性能开销;其次,通过设置核心线程数和最大线程数,可以控制线程的并发数量,避免太多线程的并发开启争夺CPU资源;最后一点就是,线程池可以对线程进行有效的管理,比如ScheduledThreadPool可以延迟N秒执行任务,并且可以每隔M秒循环执行。
Android的线程池有四种类型,针对于不同的使用场景,后面我们会逐个讲到。这里我们要知道的是,具体实现线程池的创建管理的类是ThreadPoolExecutor,它实现了Executor接口。其实Android中的四种线程池,都是在ThreadPoolExecutor的基础上,通过不同的参数配置而形成的。我们来看看ThreadPoolExecutor的一个常用构造函数:

/**     * Creates a new {@code ThreadPoolExecutor} with the given initial     * parameters and default thread factory and rejected execution handler.     * It may be more convenient to use one of the {@link Executors} factory     * methods instead of this general purpose constructor.     *     * @param corePoolSize the number of threads to keep in the pool, even     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set     * @param maximumPoolSize the maximum number of threads to allow in the     *        pool     * @param keepAliveTime when the number of threads is greater than     *        the core, this is the maximum time that excess idle threads     *        will wait for new tasks before terminating.     * @param unit the time unit for the {@code keepAliveTime} argument     * @param workQueue the queue to use for holding tasks before they are     *        executed.  This queue will hold only the {@code Runnable}     *        tasks submitted by the {@code execute} method.     * @throws IllegalArgumentException if one of the following holds:<br>     *         {@code corePoolSize < 0}<br>     *         {@code keepAliveTime < 0}<br>     *         {@code maximumPoolSize <= 0}<br>     *         {@code maximumPoolSize < corePoolSize}     * @throws NullPointerException if {@code workQueue} is null     */    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             Executors.defaultThreadFactory(), defaultHandler);    }

这里说明一下这些参数:
corePoolSize:核心线程数,除非allowCoreThreadTimeOut被设置为true,否则核心线程一直不会被回收掉。
maximumPoolSize:最大线程数量,线程池中允许创建存活的最大线程数量,如果执行的任务大于这个数量,那么任务就需要排队了。
keepAliveTime:非核心线程在空闲的时候,允许存活的时间,如果非核心线程空闲的时间超过这个值,就会被回收掉。
unit:keepAliveTime这个数值的单位,枚举类型,有TimeUnit.MILLISECONDS(ms)、TimeUnit. SECONDS(s)等。
workQueue:缓存任务的队列,线程池的execute方法会把Runnable对象缓存起来。
Executors.defaultThreadFactory():另一个构造方法里,这个参数其实是真正执行创建线程的工厂接口。
defaultHandler:这个是一个传递消息的接口。

下面我们分别来看看Android中的四种线程池:
1、FixThreadPool

public static ExecutorService newFixThreadPool(int nThreads){      return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());  }  //使用  Executors.newFixThreadPool(5).execute(r); 

从构造参数来看,FixThreadPool里面都是核心线程,如果当前线程数

public static ExecutorService newSingleThreadPool (int nThreads){      return new FinalizableDelegatedExecutorService ( new ThreadPoolExecutor (1, 1, 0, TimeUnit. MILLISECONDS, new LinkedBlockingQueue<Runnable>()) );  }  //使用  Executors.newSingleThreadPool ().execute(r); 

该线程里面只有一个存活的核心线程,所有的任务都需要排队执行,空闲的时候,该线程存活在线程池里面。

3、CachedThreadPool

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

CachedThreadPoold只会创建非核心线程,并且它所能创建的非核心线程是非常巨大的,因此也就意味着,所有的任务都能及时执行,线程不够就创建线程,空闲超过60S就会被回收。

4、SchedledThreadPool

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {        return new DelegatedScheduledExecutorService            (new ScheduledThreadPoolExecutor(1));    } public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,              new DelayedWorkQueue());    }//使用,延迟1秒执行,每隔2秒执行一次Runnable r  Executors. newScheduledThreadPool (5).scheduleAtFixedRate(r, 1000, 2000, TimeUnit.MILLISECONDS);  

ScheduledThreadPool具有定时执行和循环执行的功能。我们从构造参数中可以看到,它的核心线程只有一个,非核心线程数是接近无限大的,同时非核心线程数在空闲的时候就会被回收。

1 0
原创粉丝点击