AsyncTask也是一种异步消息处理机制,用于处理耗时操作及其UI修改。其内部封装了Thread和Handler所以我们不需要手动切换线程
首先还是看一下其简单使用
internal class MyAsyncTask(activity: SecondActivity) :
AsyncTask<String, Int, String>() {
private val reference: WeakReference<SecondActivity> = WeakReference(activity)
override fun onPreExecute() {
super.onPreExecute()
reference.get()?.mBtn?.text = "start"
}
override fun doInBackground(vararg strings: String): String? {
Log.d("cjq",strings[0])
var i = 0
while (true) {
publishProgress(i++)
Thread.sleep(20)
if (i >= 20) break
}
return "End"
}
override fun onProgressUpdate(vararg values: Int?) {
super.onProgressUpdate(*values)
Log.d("cjq","${values[0]}")
reference.get()?.mBtn?.text = "${values[0]}"
}
override fun onPostExecute(s: String) {
super.onPostExecute(s)
reference.get()?.mBtn?.text = s
}
}
开始执行任务调用
val string = arrayOf("qw","we")
mAsyncTask.execute(*string)
- 从例子来看有3个需要指定的参数类型
- pamars 输入参数,在调用execute可以传入,也是doInBackground方法的参数类型
- prograss 下载的进度类型,也是onProgressUpdate方法的参数类型
- result 返回类型,是doInBackground的返回类型也是onPostExecute的参数类型
- 从例子上我们能看到有几个重写的方法
- onPreExecute 主线程,初始化阶段,可以做一些开启弹窗等操作
- doInBackground 子线程,耗时操作执行的方法
- onProgressUpdate 主线程,更新下载进度的方法,需要在doInBackground 中调用publishProgress才会执行
- onPostExecute 主线程,结束阶段,可以执行关闭弹窗的等操作
ok,了解这些之后,我们开始往里走走
进入AsyncTask的构造函数中
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);
}
}
};
}
在构造函数中创建了一个callable对象和futureTask对象,我们看到在mWork对象中的call方法中调用了doInBackground方法,是不是就是这个方法的入口,先暂存一下
进入execute中
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只能提交一次execute,否则会报错
这个方法中调用了onPreExecute() ,所以该方法是第一个执行且还是处于主线程中,
exec是什么?我们在之前的构造函数中会找到是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);
}
}
}
在使用默认线程池时,内部使用一个双端队列来存储任务,且只能在一个任务执行完成之后才会重新调用scheduleNext()来执行下一个任务。
再看下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;
}
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
THREAD_POOL_EXECUTOR这个其实是一个线程池来执行任务。
由此发现Asynctask虽然内部维护了一个多任务的线程池,但实际上还是相当于单线程的执行
我们发现在executeOnExecutor方法中可以传入自定义的的线程池。
val executor = ThreadPoolExecutor(10,20,10,TimeUnit.SECONDS,LinkedBlockingQueue<Runnable>())
mAsyncTask.executeOnExecutor(executor)
这样就能达到同时执行多个任务的目的。
继续往下。在上面的 r 其实就是构造future时传入的worker对象,由此我们进入我们上文的call()方法中,开始执行doInBackground(),果然是在这里进行调用
我们回到之前的方法
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;
}
};
直接到postResult方法中
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
找到handler的handlemessage方法
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}
@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;
}
}
}
我们能看到在AsyncTask中通过handler将消息发送到主线程进行线程切换
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
在finish方法中判断是否是cancel状态,不是则调用onPostExecute方法。我们记得更新进度需要在doInBackground中调用publishProgress,来看下具体是怎么更新的
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
通过handler来进行发送,在handleMessage中再调用onProgressUpdate方法。
至此所有方法的调用已全部出现
总结一下:
AsyncTask 在其内部通过handler和Thread进行线程的切换
在默认情况下Asynctask内部维护了具体大小的一个线程池,但是实际上是单线程执行。(在3.0以前,最大支持128个线程的并发,10个任务的等待。在3.0以后,无论有多少任务,都会在其内部单线程执行),但可以传入自定义的线程池来完成多任务并行
网友评论