1.new AsyncTask();
corePoolSize the number of threads to keep in the pool, even if they are idle, unless
maximumPoolSize the maximum number of threads to allow in the pool
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.
unit the time unit for the
workQueue the queue to use for holding tasks before they are executed. This queue will hold only the
threadFactory the factory to use when the executor creates a new thread
/**
* 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
return postResult(doInBackground(mParams));
}
};
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 occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
将
mWorker和
mFuture
实例化了
2.执行execute()方法
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;
}
(1)由
mStatus
= Status.
RUNNING
;知
execute()方法只能执行一次
(2)由
mWorker
.
mParams
= params;知通过
mWorker可以获取
params(URL),由1知
通过
mFuture
可以获取
mWorker
3.执行exec.execute(mFuture)
exec是
SerialExecutor实例的引用,他的execute()方法
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
在这个方法中将FutureTask对象
mFuture
插入到任务队列
mTasks中
4.最后都会调用scheduleNext()方法
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
由
mActive
=
mTasks
.poll()知,
mActive
是从
mTasks中取出的任务,其中,
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 1;
public static final Executor THREAD_POOL_EXECUTOR
=
new
ThreadPoolExecutor(
CORE_POOL_SIZE
,
MAXIMUM_POOL_SIZE
,
KEEP_ALIVE
,
TimeUnit.
SECONDS
,
sPoolWorkQueue
,
sThreadFactory
);
(1)
CORE_POOL_SIZE
:
核心线程数,默认会一直存活,即使处于闲置状态(可以通过
设置
allowCoreThreadTimeOut,闲 置的
超时时间)
(2)MAXIMUM_POOL_SIZE
:
线程池所能容纳的最大线程数,当活动线程超过这个数,后续的新任务会被阻塞
KEEP_ALIVE
:
非
核心线程闲置时的超时时长(当
THREAD_POOL_EXECUTOR的
allowCoreThreadTimeOut为true时,
KEEP_ALIVE同样会作用于核心线程
)
(3)TimeUnit.
SECONDS:
KEEP_ALIVE
的单位,这里表示是秒
(4)sPoolWorkQueue
:
线程池的任务队列,调用execute方法提交的Runnable对象会储存在这个参数中
(5)sThreadFactory
:
线程工厂,为线程池提供创建新线程的功能。
ThreadPoolExecutor的API解释
allowCoreThreadTimeOut
is set
keepAliveTime
argument
Runnable
tasks submitted by the
execute
method.
THREAD_POOL_EXECUTOR
是一个线程池,
有一个线程池,且最大支持128的线程并发,加上长度为10的阻塞队列。
通过scheduleNext
方法得知,如果现在没有正在活动的
AsyncTask,就会从
mTasks
中取出一个任务执行
,
AsyncTask是串行执行的。
5.最终会执行mFuture的run方法
在
FutureTask的构造方法中
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
this
.
callable接收的就是mWorker,
mFuture的run方法中
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
最终会调用 c.
call();也就是mWorker的call()方法
6.mWorker的call()方法
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
将
mTaskInvoked设置为
true
,表明当前任务已经被调用。然后执行
doInBackground方法,由WorkerRunnable的构造函数和AsyncTask的execute方法知:
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
mParams就是execute方法中传递过来的参数,此方法结束后将其返回值交给postResult方法
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
sHandler
发送了一个what=
MESSAGE_POST_RESULT,obj的第一个参数是this(当前
AsyncTask
)消息
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
所以
mTask
指的就是当前
AsyncTask
7.InternalHandler构造方法
private static final InternalHandler sHandler = new InternalHandler();
private static class InternalHandler extends Handler {
@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;
}
}
}<span style="font-size:18px;color:#333333;font-family: Consolas; line-height: 1.5; font-weight: bold; background-color: rgb(255, 255, 255);"> </span>
sHandler
在主线程中创建,最后调用
mTask
的finish方法,即当前
AsyncTask的finish方法
8.AsyncTask的finish方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
调用过
isCancelled方法,则执行
onCancelled(result);否则执行
onPostExecute(result);
9总结:在实例化
AsyncTask时会实例化
mWorker
(
WorkerRunnable
)
和
mFuture
(
FutureTask<Result
),
执行
AsyncTask的
execute方法时,会将
mFuture(
FutureTask,继承自
RunnableFuture,继承自
Runnable接口
)加入线程池中,最终会执行
mFuture的run方法,此方法执行
mWorker的call方法,call方法中执行
doInBackground方法并将其结果使用handle发送,接收到消息后,如果
isCancelled()返回true执行
onCancelled方法,否则执行
onPostExecute方法。这样
AsyncTask的
整个流程就执行完毕了