android 多线程学习1:一些基础
android 多线程学习2:线程的创建与方法分析
android 多线程学习3:synchronized与volatile与线程安全对象
android 多线程学习4:线程池ThreadPoolExecutor
android 多线程学习5:AsyncTask
android 多线程学习6:HandlerThread
android 多线程学习7:Handler消息处理机制
线程池的优点:
1. 通过线程池中线程的重用,减少创建和销毁线程的性能开销;
2. 控制线程池中的并发数,避免大量的线程争夺CPU资源造成阻塞;
3. 对线程进行管理,比如使用ScheduledThreadPool来设置延迟N秒后执行任务,并且每隔M秒循环执行一次;
线程池的构造参数:
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @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.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:
* {@code corePoolSize < 0}
* {@code keepAliveTime < 0}
* {@code maximumPoolSize <= 0}
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
int corePoolSize:
核心线程数,除非allowCoreThreadTimeOut被设置为true,否则它闲着也不会死
int maximumPoolSize:
最大线程数,活动线程数量超过它,后续任务就会排队
long keepAliveTime:
超时时长,作用于非核心线程(allowCoreThreadTimeOut被设置为true时也会同时作用于核心线程),闲置超时便被回收
TimeUnit unit:
枚举类型,设置keepAliveTime的单位,有TimeUnit.MILLISECONDS(ms)、TimeUnit. SECONDS(s)等
BlockingQueue
缓冲任务队列,线程池的execute方法会将Runnable对象存储起来
ThreadFactory threadFactory:
线程工厂接口,只有一个new Thread(Runnable r)方法,可为线程池创建新线程。一般使用默认即可 Executors.defaultThreadFactory()
RejectedExecutionHandler handler:
拒绝策略 (当任务太多导致工作队列满时的处理策略)。一般使用默认策略即可
核心线程:固定线程数,闲置也不会被销毁 (ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true时,keepAliveTime同样会作用于核心线程)
非核心线程:非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收
线程池的工作流程:
说明:
1、如果工作线程数小于核心线程池上限(CorePoolSize),则直接新建一个工作线程并执行任务;
2、如果工作线程数大于等于CorePoolSize,则尝试将任务加入到队列等待以后执行。如果队列已满,则在总线程池未满的情况下(CorePoolSize ≤ 工作线程数 < maximumPoolSize)新建一个工作线程立即执行任务,否则执行拒绝策略。
线程池关闭
threadPoolExecutor.shutdown()
: 将线程池切换到SHUTDOWN状态(如果已经停止,则不用切换),并调用interruptIdleWorkers方法中断所有空闲的工作线程,最后调用tryTerminate尝试结束线程池threadPoolExecutor.shutdownNow()
: 将线程池的状态至少置为STOP,同时中断所有工作线程(无论该线程是空闲还是运行中),同时返回任务队列中的所有任务
Android中的四类线程池
1. Executors.newFixedThreadPool(3)
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
特点:
1. 线程数量固定(用户自定义)
2. 核心线程数=最大线程数,且只有核心线程,所以当线程处于空闲状态时,它们并不会被回收,除非线程池关闭
3. 线程池队列无限大(其实队列大小为Integer.MAX_VALUE,即2的31次方-1)
4. 由于线程不会回收,FixThreadPool会更快地响应外界请求
2. Executors.newSingleThreadExecutor()
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
特点:
1. 只有一个核心线程
2. 核心线程数=最大线程数=1,且只有核心线程,所以当线程处于空闲状态时,它们并不会被回收,除非线程池关闭
3. 线程池队列无限大(其实队列大小为Integer.MAX_VALUE,即2的31次方-1)
4. 确保所有任务都在同一线程中按顺序完成,因此不需要处理线程同步的问题。
3. Executors.newCachedThreadPool()
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
特点:
1. 无核心线程
2. 非核心线程无限多(Integer.MAX_VALUE)。所有线程都活动时,会为新任务创建新线程,否则利用空闲线程处理任务。线程超时时间为60秒,所以空闲线程会被超时回收,所以线程池中有0个线程的可能(此时几乎不占用系统资源)。
3. 无存储队列。SynchronousQueue相当于一个空集合,导致任何任务都会被立即执行。
4. 适合处理高并发,且耗时较少的任务。
4. Executors.newScheduledThreadPool(3)
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());
}
特点:
1. 线程数量固定(用户自定义)
2. 非核心线程无限多(Integer.MAX_VALUE)。非核心线程超时时间为10秒,所以空闲线程会被超时回收。
3. 拥有延迟执行存储队列。
4. 用于执行定时任务和具有固定周期的重复任务。
使用:
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
//延迟任务:延迟1000ms开始执行
executorService.schedule(new Runnable() {
@Override
public void run() {
//do something
}
}, 1000, TimeUnit.MILLISECONDS);
//周期任务:延迟1000ms开始执行,每5000ms执行一次
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//do something
}
}, 1000, 5000, TimeUnit.MILLISECONDS);
//定时任务:10分钟后执行
executorService.schedule(new Runnable() {
@Override
public void run() {
//do something
}
}, 10, TimeUnit.MINUTES);
//定时延迟任务:延迟1000ms开始执行,10分钟后执行
executorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
//do something
}
}, 1000, 10, TimeUnit.MINUTES);
线程池的使用场景
- 频繁执行的后台任务,比较适合使用线程池。(如:网络请求)
- 单次执行,或后台短暂运行的任务,可使用AyncTask或HandlerThread或Thread
(部分内容参考于网络,如有不妥,请联系删除~)