概要
通常在程序中执行耗时任务会用到线程,在大量使用线程情况下又会用到线程池。本文将介绍Android开发中与线程相关的各个类,让大家对线程管理有个大概的认知,下面先从线程池说起。
线程池
当程序中有大量的网络请求时,就会频繁的创建和销毁线程,这时就会造成过大的性能开销,同时当大量线程一起工作的时候,也会导致相互抢占CPU资源的现象发生,严重时会发生线程阻塞等现象。因此传统的线程是不可控的,频繁的创建和销毁会导致过多的系统资源开销。
线程池的作用
- 通过线程池中线程重用,减少创建和销毁线程的性能开销
- 能控制线程池中的并发数,避免大量的线程争夺CPU资源造成阻塞
- 能够对线程进行管理,如使用ScheduledThreadPool来设置延迟执行或周期执行
ThreadPoolExecutor
ThreadPoolExecutor是Android四类线程池的基类,它们都是通过配置不同参数来实现不同特性的线程池。因此需要重点关注下各个参数的意思。
/**
* 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, //枚举类型,设置keepAliveTime的单位,有TimeUnit.MILLISECONDS(ms)、TimeUnit. SECONDS(s)等
BlockingQueue<Runnable> workQueue)
当调用execute()方法把任务加入到线程池,这个任务的执行流程如下(workingThreadSize表示线程池中当前线程数量)
//任务提交时的执行顺序 corePoolSize –> workQueue –> maximumPoolSize
if (workingThreadSize < corePoolSize) {
创建新线程来处理任务,即使线程池中的其他线程是空闲的
} else {
if (workQueue未满) {
将任务放入队列,等待线程空闲后执行
} else {
if (workingThreadSize < maximumPoolSize) {
创建新的非核心线程执行任务
} else {
任务不能执行,抛出异常
}
}
}
Android中的四类线程池
FixThreadPool
只有核心线程,并且数量固定,也不会被回收,能够更加快速地响应外界的请求。
任务队列是LinkedBlockingQueue,大小非常大(MAX_VALUE = 0x7fffffff),这种情况下maximumPoolSize不会起作用,不会有非核心线程。
/**
* 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>());
}
SingleThreadExecutor
只有一个核心线程,所有任务都在同一线程中按顺序完成,不需要处理线程同步的问题,同newFixedThreadPool(1)。
/**
* 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<Runnable>()));
}
CachedThreadPool
corePoolSize为零,maximumPoolSize非常大(MAX_VALUE = 0x7fffffff)。具备超时机制,全部回收时几乎不占系统资源,无线程可用时会新建,任何任务到来都会立刻执行,不需要等待。用于执行大量、耗时少的线程任务。
任务队列是SynchronousQueue,相当于一个空集合,任何队列中的任务都会被立即执行。
/**
* 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<Runnable>());
}
ScheduleThreadPool
corePoolSize固定,maximumPoolSize非常大(MAX_VALUE = 0x7fffffff),主要用于执行定时任务以及有周期性任务。
任务队列DelayedWorkQueue是一个无界阻塞队列,内部维持了一个以任务启动时间升序排序的二叉树数组,启动时间最靠前的任务即数组的首个位置上的任务。
corePoolSize为0时,ScheduledThreadPool将以非核心线程工作,并且最多只会创建一个非核心线程。
执行定时任务时,如果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) {
ThreadPoolExecutor(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue());
}
线程队列
LinkedBlockingQueue
是一个无界缓存等待队列,大小非常大(MAX_VALUE = 0x7fffffff)。当前执行的线程数量达到corePoolSize的数量时,剩余的元素会在阻塞队列里等待。(所以在使用此阻塞队列时maximumPoolSizes就相当于无效了),每个线程完全独立于其他线程。生产者和消费者使用独立的锁来控制数据的同步,即在高并发的情况下可以并行操作队列中的数据。
SynchronousQueue
SynchronousQueue没有容量,是无缓冲等待队列,是一个不存储元素的阻塞队列,会直接将任务交给消费者,必须等队列中的添加元素被消费后才能继续添加新的元素。
拥有公平(FIFO)和非公平(LIFO)策略,非公平侧罗会导致一些数据永远无法被消费的情况。
使用SynchronousQueue阻塞队列一般要求maximumPoolSizes为无界,避免线程拒绝执行操作。
DelayedWorkQueue
DelayedWorkQueue是一个无界阻塞队列,内部维持了一个以任务启动时间升序排序的二叉树数组,启动时间最靠前的任务即数组的首个位置上的任务。
线程相关类
HandlerThread
/**
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
*/
public class HandlerThread extends Thread {
...
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
...
}
HandlerThread是一个含有Looper循环的Thread,使用前需要调用start方法,使用结束后需要调用quit方法释放Looper循环。
使用场景:需要在子线程中开启Looper循环来处理消息的,并可通过主线程Handler与子线程通信。
使用步骤:
1.创建HandlerThread,并调用start方法
2.创建自定义Handler并实现handleMessage方法,在Handler中传入HandlerThread的Looper对象,这样就绑定到了子线程的Looper。
3.使用自定义Handler的sendmessage方法向Looper对象里面发送消息。
IntentServer
public abstract class IntentService extends Service {
...
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
...
}
IntentServer是一个包含HandlerThread线程的Server,需要实现其onHandleIntent方法,该方法在线程中执行,一次使用后会自动退出,不用自己管理其生命周期。常用于后台下载等独立的耗时任务。
AsyncTask
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*
* @hide
*/
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
AsyncTask源码里面有两个线程池:SerialExecutor默认的串行线程池和THREAD_POOL_EXECUTOR并行执行任务的线程池,线程任务执行完成后利用Handler通知到UI线程。
我们先看构造函数,首先mHandler绑定到了MainLooper,所以后续任务就可以使用mHandler通知到主线程。随后创建了一个mWorker对象,并把该对象绑定到mFuture 中。mFuture是一个封装了我们的后台任务的FutureTask对象,FutureTask类实现了FutureRunnable接口,通过这个接口可以方便的取消后台任务以及获取后台任务的执行结果,详情请百度:Callable、Future和FutureTask。
接下来我们看execute方法,该方法调用了默认的SerialExecutor线程池来处理任务,因此AsyncTask的任务都是串行执行的。通过源码分析我们可以看到SerialExecutor所完成的工作主要是把构造函数创建的mFuture任务加到任务缓存队列中,而真正执行任务的是THREAD_POOL_EXECUTOR。如果需要并行执行,请直接调用executeOnExecutor(THREAD_POOL_EXECUTOR, params)方法,把指定线程池为THREAD_POOL_EXECUTOR。
从源代码可以看出AsyncTask本质上是Handler + 线程池的封装而已。只要仔细阅读源码,也不难理解其工作流程。