4 Fragment
4.1 Fragment的使用
4.2 FragmentTransaction
4.3 Fragment与Activitiy之间的通信
4.3 Fragment的回退栈
Fragment懒加载
Fragment与View的状态保存与恢复
Fragment与大型数据缓存
5 线程池
5.1 线程池的优点
.重用线程池中的线程,避免因为线程的创建和销毁所带来的性能开销
.能有效控制线程池的最大并发数,避免大量的线程之间因互相抢占系统资源而导致的阻塞现象
.能够对线程进行简单的管理,并提供定时执行以及指定时间间隔循环执行等功能
5.2 Api实现的四种不同特性的线程池
Android中利用ThreadPoolExecutor来实现不同特性的线程池.分别为:FixThreadPool,CachedThreadPool,SingleThreadExecutor,ScheduleThreadPool
5.2.1 SingleThreadExecutor
- 特点:只有一个核心线程(保证所有任务按照指定顺序在一个线程中执行,不需要处理线程同步的问题)
- 应用场景:不适合并发
- 具体使用:Executors.newSingleThreadExecutor()
- 具体的定义:
/**- Creates an Executor that uses a single worker thread operating
- off an unbounded queue. (Note however that if this single
- thread terminates due to a failure during execution prior to
- shutdown, a new one will take its place if needed to execute
- subsequent tasks.) Tasks are guaranteed to execute
- sequentially, and no more than one task will be active at any
- given time. Unlike the otherwise equivalent
- {@code newFixedThreadPool(1)} the returned executor is
- guaranteed not to be reconfigurable to use additional threads.
- @return the newly created single-threaded Executor
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
5.2.2 FixThreadPool(定长线程池)
- 特点:只有核心线程&不会被回收,线程数量固定,任务队列无大小限制(超出的线程任务会在队列中等待)
- 应用场景:控制线程最大并发数
- 具体使用:Executors.newFixedThreadPool()来创建
- 具体的定义:
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
5.2.3 ScheduleThreadPool(定时线程池)
- 特点:核心线程数量固定,非核心线程数量无限制(闲置时马上回收)
- 应用场景:执行定时,周期性任务
- 具体实现:Executors.newScheduledThreadPool()创建
- 具体的定义:
/**- Creates a thread pool that can schedule commands to run after a
- given delay, or to execute periodically.
- @param corePoolSize the number of threads to keep in the pool,
- even if they are idle
- @return a newly created scheduled thread pool
- @throws IllegalArgumentException if {@code corePoolSize < 0}
/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
/* - Creates a new {@code ScheduledThreadPoolExecutor} with the
- given core pool size.
- @param corePoolSize the number of threads to keep in the pool, even
-
if they are idle, unless {@code allowCoreThreadTimeOut} is set
- @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
5.2.4 CachedThreadPool(可缓存线程池)
- 特点:只有非核心线程,线程数据不固定(可无限大),灵活回收空闲线程(具备超时机制,全部回收时不占系统资源).任何线程任务到来都会立刻执行,不需要等待
- 应用场景:执行大量,耗时少的线程任务
- 具体实现:Executors.newCachedThreadPool()
- 具体的定义
/**- Creates a thread pool that creates new threads as needed, but
- will reuse previously constructed threads when they are
- available. These pools will typically improve the performance
- of programs that execute many short-lived asynchronous tasks.
- Calls to {@code execute} will reuse previously constructed
- threads if available. If no existing thread is available, a new
- thread will be created and added to the pool. Threads that have
- not been used for sixty seconds are terminated and removed from
- the cache. Thus, a pool that remains idle for long enough will
- not consume any resources. Note that pools with similar
- properties but different details (for example, timeout parameters)
- may be created using {@link ThreadPoolExecutor} constructors.
- @return the newly created thread pool
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
5.3 自定义线程池
- Android线程池的概念来自于Java的Executor接口,此接口的真正的实现类为ThreadPoolExecutor
- ThreadPoolExecutor的构造方法提供了一些参数来配置线程池.
5.3.1 具体的构造方法
public ThradPoolExecutor(int corePoolSize,int maximumPoolSize,
long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
5.3.2 参数的理解
- corePoolSize:核心线程数,默认情况下,核心线程即使闲置也会一直存活.但是可以通过设置allCoreThreadTimeOut为true,来允许其等待超时,并用keepAliveTime来设置超时时间
- maximumPoolSize:线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞.
- keepAliveTime:非核心线程的超时时间.当然设置了allCoreThreadTimeOut为true时,也会作用于核心线程.
- unit:用于指定keepAliveTime参数的时间单位,是一个枚举类型.常用的有TimeUnit.MILLISECONDS和TimeUnit.SECONDS
- workQueue:线程池中的任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中
- ArrayBlockingQueue:基于数组结构的有界阻塞队列,此队列按FIFO(先进先出)原则对元素进行排序.
- LinkedBlockingQueue:基于链表结构的阻塞队列,此列表按FIFO(先进先出)排序元素,吞吐量要高于ArrayBlockingQueue.静态工厂方法Executors.newFixedThreadPool()使用了这个队列
- SynchronousQueue:一个不存储元素的阻塞队列.每个插入操作必须等到另一个线程调用移除操作,否则插入操作一直处于阻塞状态.吞吐量要高于LinkedBlockingQueue,静态工厂方法Executors.newCachedThreadPool使用了这个队列
- PriorityBlockingQueue:一个具有优先级的无线阻塞队列.
- threadFactory:线程工厂,为线程池提供创建新的线程的功能.threadFactory是一个接口,只有一个方法:public abstract Thread newThread(Runnable r)
- RejectedExecutionHandler: 拒绝策略.线程池已经关闭或者是最大线程数和任务队列已经饱和,无法再接收新的任务时,在使用execute()来提交新的任务时将会拒绝.而默认的策略是抛一个RejectedExecutionException异常.
5.3.3 执行任务时的策略
以下用currentSize表示线程池中当前线程数量
- currentSize<corePoolSize,将会直接启动一个核心线程来执行任务
- currentSize>=corePoolSize,任务会被插入到任务队列中排队等待执行
- 任务队列已满,currentSize<maximumPoolSize,会立刻启动一个非核心线程来执行任务
- 任务队列已满,currentSize>maximumPoolSize,会拒绝执行任务,ThreadPoolExecutor会调用RejectedExecutionHandler的rejectedExecution方法来通知调用者
5.3.4 使用
- 使用构造函数创建对象
- 使用execute(Runnable runnable)向线程池提交任务
- 使用shutdown()方法来中断(interrupt())所有没有正在执行任务的线程
使用shutdownNow()来停止(stop)所有正在执行或暂停任务的线程.
建议:一般调用shutdown()来关闭线程池;若任务不一定要执行完,则调用shutdownNow()
参考到地址
基础讲的比较好的一篇:https://www.jianshu.com/p/0e4a5e70bf0e
结合代码进行讲解:https://www.jianshu.com/p/7b2da1d94b42
讲解的特别基础好理解:https://blog.youkuaiyun.com/l540675759/article/details/62230562
参考书籍:Android开发艺术探索
4 AsyncTask的缺陷和问题,说说他的原理
4.1 基础知识
4.2 缺陷
鸡汤一则:积累是一个漫长的过程,需要的是不断的刷新与整理.最终才能由量变到质变!