作用
AsyncTask是android开发中使用的一种轻量级异步任务类,其作用是在线程池中执行后台的任务,并在执行过程中将执行进度传递给主线程,当任务执行完毕后,将最终结果传递给主线程。
源码分析
在源码分析前,我们知道AsyncTask提供了4个核心的方法
- onPreExecute() 是在异步调用执行之前,异步任务执行前的初始化工作可以在该方法中执行,我们知道这个方法是执行在主线中的
- doInBackground(Params...params) 是在线程池中执行,任务开始后到任务结束之前,用于执行异步任务
- onProgressUpdate(Progress...values) 是在主线程中进行执行,任务开始后到任务结束之前,用于更新进度
- onPostExecute(Result result) 是在主线程中进行执行,异步任务执行之后,将异步任务的执行结果传递给主线程。
这里面有些方法是在主线程、有些是在异步线程中进行执行的,那么这里就涉及到了线程的切换,我们进行线程的切换,就想到Handler,这里面执行线程的结果,所以我们需要通过Future来进行获取到执行的结果
-
在AsyncTask中我们使用到了线程池,所以首先我们需要创建一个线程池,那对于线程池,我们只需要一个线程池,故我们通过在静态初始化块中进行创建。创建一个线程池,我们需要知道:
- 核心线程的数目
- 线程池的最大的线程数目
- 空闲线程池的存活时间
- 空闲线程池的存活时间单位
- 线程池中的阻塞队里
- 线程的创建工厂
//获取设备CPU的个数
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//将核心线程的数目限制在2~4个之间
private static final int CORE_POOL_SIZE = Math.max(2,Math.min(CPU_COUNT - 1, 4))
//设置普通线程数为CPU个数的2倍多一个
private static final int MAXIMUM_POOL_SIZE= CPU_COUNT*2+1;
//设置空闲线程的存活时间为30s
private static final int KEEP_ALIVE_SECONDS = 30
//创建一个线程工厂
private static final ThreadFactory sThreadFactory = new ThreadFactory(){
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r){
return new Thread(r,"AsyncTask #"+mCount.getAndIncreament())
}
}
//创建一个容量为128的阻塞队列
private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128);
//定义一个线程池
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.allowCoreTheadTimeOut(true)
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
- 我们需要创建一个Handler来进行线程间切换,同时为了能获取到线程执行的结果,我们需要使用FutureTask,以及继承自Callable的任务
//用来在类中只有一个sHandler,和创建多少个对象无关
private static InternalHandler sHandler;
private final Handler mHandler;
private final WorkerRunnable<Params,Result> mWorker;
private final FutureTask<Result> mFuture;
private AtomicBoolean mTaskInvoked = new AtomicBoolean();
private AtomicBoolean mCancelled = new AtomicBoolean();
private static final int MESSAGE_POST_RESULT = 0x1;
public AsyncTask(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;
try{
//优先级设置为后台线程
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//执行耗时操作
result = doInBackground(mParams);
//将进程中未执行的命令,一并送往CPU处理
Binder.flushPendingCommands();
}catch(Throwable tr){
mCancelled.set(true);
throw tr;
}finally{
//通过Handler来传递结果
postResult(result);
}
return result;
}
};
mFuture = new FutureTask<Result>(mWorker){
@Override
protected void done(){
try{//返回结果
postResultIfNotInvoked(mFuture.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)
}
};
}
private void postResultIfNotInvoked(Result result){
final boolean wasTaskInvoked = mTaskInvoked.get();
if(!wasTaskInvoked){
postResult(result);
}
}
/**
通过Handler将消息传递给UI线程进行处理
**/
private Result postResult(Result result){
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,new AsyncTaskResult<Result>(this,result));
message.sendToTarget();
return result;
}
}
public static Handler getMainHandler(){
synchronized(AsyncTask.class){
if(sHandler == null){
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
private Handler getHandler(){
return mHandler;
}
private static class InternalHandler extends Handler(){
public InternalHandler(Looper looper){
super(looper);
}
@Override
public void handlerMessage(Message msg){
AsyncTaskResult<?> result = (AsyncTaskResult<?>)msg.obj;
switch(msg.what){
case MESSAGE_POST_RESULT:
result.mTask.finish(result.mTask.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private static abstract class WorkerRunnable<Params,Result> implements Callable<Result>{
Params[] mParams;
}
//线程中传递的数据结构
private static class AsyncTaskResult<Data>{
final AsyncTask mTask;//持有当前的对象
final Data[] mData;//返回的数据
AsyncTaskResult(AsyncTask task,Data...data){
this.mTask = task;
this.mData = data;
}
}
private void finish(Result result){
//判断是否取消了,取消了则调用取消的接口,否则调用onPostExecute(),当前任务状态置为完成
if(isCancelled()){
onCancelled(result);
} else{
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
- 调用线程池,创建一个任务调度的线程池SERIAL_EXECUTOR,其中有一个任务队列,将任务放进队列中,并不断地从队列中取任务交给线程池进行执行
private final static Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor{
//双端队列
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnalbe mActive;
public synchronized void execute(final Runnalbe runnbale){
//向队列中插入一个元素,并返回true,如果队列已满,返回false
mTaks.offer(new Runnable(){
public void run(){
try{
runnable.run();
}finally{
scheduleNext();
}
}
});
if(mActive == null){
scheduleNext();
}
}
/**
* 取出队列头部的元素,并从队列中移除交给线程池执行,队列为空,返回null
**/
protected synchronized void scheduleNext(){
if((mActive == mTask.pool()) != null){
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
public final AsyncTask<Params,Progress,Result> executeOnExecutor(Executor executor,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;
}