写Android App的童鞋无可避免都会遇到线程这个东西,对于一些耗时的工作,我们都应该尽可能的把工作放到线程中去完成。但是若每个耗时操作都去开启一个线程,那么就会导致app内的线程数大量增加,对于某些手机,比如华为的,其在线程超过500时会直接OOM。因此避免这些情况的最好方法是使用线程池进行统一管理。我们可在app级别定义一些线程池,对全局的线程进行管理。接下来我就总结一下常见的线程池创建方法。
下图为常见的几种线程池类以及对应的核心线程数和非核心线程数统计表
线程池类 | 核心线程数(corePoolSize) | 非核心线程数 |
---|---|---|
ThreadPoolExecuteor | 传入的核心线程个数(corePoolSize) | 传入的线程总数-传入的核心线程个数( maximumPoolSize - corePoolSize ) |
FixedThreadPool | 传入的核心线程个数(corePoolSize) | 0 |
CachedThreadPool | 0 | Integer.MAX_VALUE |
ScheduledThreadPool | 传入的核心线程个数(corePoolSize) | Integer.MAX_VALUE -corePoolSize |
SingleThreadExecutor | 1 | 0 |
设置线程池的用到的类:
1.ThreadPoolExecutor【本体】
ThreadPoolExecutor threadPoolExecutor = ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
复制代码
* @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)
复制代码
其中各个参数的含义为
-
corePoolSize 核心线程数
-
maximumPoolSize 线程池最多的线程数
-
keepAliveTime 非核心线程数的保活时间
-
workQueue 存放线程的工作队列
下面四种通过工厂类Executors产生线程池,其最终调用的仍旧是ThreadPoolExecutor的构造方法。
2. FixedThreadPool 【包装体】
创建方法
Executors.newFixedThreadPool(int)
复制代码
最后执行的代码
new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
复制代码
3. CachedThreadPool
Executors.newCachedThreadPool();
复制代码
new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>())
复制代码
4. ScheduledThreadPool
new ScheduledThreadPool(int);
复制代码
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
复制代码
private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
复制代码
5. SingleThreadExecutor
newSingleThreadExecutor();
复制代码
new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
复制代码