简介
AsyncTask是一个轻量级的异步任务类,它可以在线程池中执行后台任务,然后把执行的进度和结果传递给主线程并且在主线程中更新UI。
需要注意的是
- AsyncTask 不可重复执行。
- AsyncTask的构造和运行都需要在主线程中处理。
- 不适合执行特别耗时的任务
- 在目前的版本中,如果不特别处理,所有的AsyncTask将采用串行执行。
使用
这里直接上代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
new MyAsyncTask().execute("233333");
}
public static class MyAsyncTask extends AsyncTask<String, Integer, String> {
private static final String TAG = "MyAsyncTask";
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG, "onPreExecute: ");
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d(TAG, "onPostExecute: "+s);
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.d(TAG, "onProgressUpdate: "+values[0]);
}
@Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground: "+strings.length);
for (int i=0;i<100;i++){
publishProgress(i);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return strings[0];
}
}
源码阅读
阅读AsyncTask的源码,我们从excute方法入手
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
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没有执行过的时候,才能执行,否则的话,就会抛出异常。
在执行以后,首先将状态更改为运行,然后执行了onPreExecute()方法,然后将参数保存到了mWorker,随后运行了语句exec.execute(mFuture);,而这里的exec,我们通过上面的代码很明显就可以看到是上面的sDefaultExecutor。
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
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);
}
}
}
这里可以看到AsyncTask内部实现了一个SerialExecutor,而这个类的功能非常简单,就是构造一个Runnable方法,将原来的run方法包裹起来,然后判断当前线程池是否有Runnable方法正在运行,如果没有的话,就手动去调用THREAD_POOL_EXECUTOR 线程池。正是由于这种处理方法,如果第一个AsyncTask正在执行,当第二个AsyncTask进来的时候,只会将新构造的Runnable方法保存进SerialExecutor,而不会直接将其添加THREAD_POOL_EXECUTOR线程池。
那么这个THREAD_POOL_EXECUTOR又是何方神圣呢?
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
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.getAndIncrement());
}
};
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
这里可以看到THREAD_POOL_EXECUTOR线程池是一个核心线程为 CPU_COUNT + 1,线程池最大线程数为 CPU_COUNT * 2 + 1;,任务队列最大为128的线程池。
有人可能在这里就要犯迷糊了,不是说AsyncTask是串行运行嘛。为啥这里需要建这么大一个线程池,应该一个SingleThreadExecute就够用了啊。你说的没错,这是正常情况。这不是我们AsyncTask不是还提供了并发执行的方法executeOnExecutor嘛。这里的线程池多余了这么多的资源,就是为了这个准备的。
好了,这里我们把exec搞清楚了,接下来我们看**exec.execute(mFuture);**中的mFuture
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(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);
}
}
};
}
这里的FutureTask的就是进化版的runnable,实现了Runnable接口和Future接口。一旦线程开始运行,就会执行call中的方法,然后就会执行doInBackground方法。
这里的doInBackground方法,就是我们在AsyncTask中实现的doInBackground方法。之后线程就会阻塞在这里,而我们在doInBackground中,如果想更新进度,都会去调用AsyncTask的publishProgress方法。所以我们来看下publishProgress的实现。
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
这里的逻辑就非常简单了,就是使用了handler然后在ui线程中调用onProgressUpdate去更新进度。
当doInBackground执行完毕之后,会返回一个result.
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
然后又会调用postResult,将最后的result通过handler发送到finish方法。所以finish方法也是在UI线程中执行的。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
而根据代码,finish方法,如果为正常结束的话,又会调用onPostExecute方法,所以onPostExecute也是在UI线程中执行的。
好了,正常的逻辑,我们都已经走完了。搞定睡觉!