AsyncTaskDemo在我的上一篇博客里,现在就根据我上一篇博客的小demo来具体分析AsyncTask到底是怎样工作的
我们在demo的mainActivity中调用了这样两段代码
<span style="white-space:pre"> </span>MyAsyncTask asyncTask = new MyAsyncTask(textView,progressBar);
<span style="white-space:pre"> </span>asyncTask.execute(1000);
我首先新建了一个MyAsyncTask类,这个类继承于AsyncTask,从代码中不难看出
package com.example.asynctaskdemo;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;
/*
* Params:输入参数。对应的是调用自定义的AsyncTask的类中调用excute()方法中传递的参数。如果不需要传递参数,则直接设为Void即可。
Progress:子线程执行的百分比
Result:返回值类型。和doInBackground()方法的返回值类型保持一致。
*/
public class MyAsyncTask extends AsyncTask<Integer, Integer, String> {
private TextView textview;
private ProgressBar progressBar;
// 因为我们需要实时更新UI,所以将控件对象传入进来好进行更新
public MyAsyncTask(TextView textview, ProgressBar progressBar) {
// TODO Auto-generated constructor stub
super();
this.textview = textview;
this.progressBar = progressBar;
}
// 这个方法运行在子线程
//不可以进行UI操作
//对应第一个参数
@Override
protected String doInBackground(Integer... params) {
// TODO Auto-generated method stub
Download download = new Download();
int i = 0;
for (i = 0; i <= 100; i++) {
download.start();
//实际上调用onProgressUpdate方法
publishProgress(i);
}
//对应第三个参数,这个返回值返回给onPostExecute方法
return i + params[0].intValue() + "";
}
//doInBackground执行完毕以后调用
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
textview.setText("异步调用执行完毕" + result);
}
//doInBackground之前调用
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
textview.setText("异步调用正在执行");
}
//对应第二个参数
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
progressBar.setProgress(values[0]);
}
}
我构造MyAsyncTask的时候将两个控件对象传入,方便调用控件进行实时更新
这里补充一些AsyncTask构造方法
/**
* 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);
}
}
};
}
private final WorkerRunnable<Params, Result> mWorker;
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
Callable是java的源码,查了一下,大致是和Runnable差不多,不同的是Runnable没有返回值且不能抛出异常,Callable有返回值且抛出可能发生的异常
callabll源码不在Android里,解压java里的src得到了callable源码
package java.util.concurrent;
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
而FutureTask也是java里面多线程的源码
package java.util.concurrent;
import java.util.concurrent.locks.LockSupport;
public class FutureTask<V> implements RunnableFuture<V> {
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int NORMAL = 2;
private static final int EXCEPTIONAL = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTING = 5;
private static final int INTERRUPTED = 6;
private Callable<V> callable;
private Object outcome;
private volatile Thread runner;
private volatile WaitNode waiters;
@SuppressWarnings("unchecked")
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public boolean isCancelled() {
return state >= CANCELLED;
}
public boolean isDone() {
return state != NEW;
}
public boolean cancel(boolean mayInterruptIfRunning) {
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
return true;
}
/**
* @throws CancellationException {@inheritDoc}
*/
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
protected void done() { }
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
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 = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
protected boolean runAndReset() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return false;
boolean ran = false;
int s = state;
try {
Callable<V> c = callable;
if (c != null && s == NEW) {
try {
c.call(); // don't set result
ran = true;
} catch (Throwable ex) {
setException(ex);
}
}
} finally {
runner = null;
s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
return ran && s == NEW;
}
private void handlePossibleCancellationInterrupt(int s) {
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield();
}
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
for (;;) {
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
private void removeWaiter(WaitNode node) {
if (node != null) {
node.thread = null;
retry:
for (;;) { // restart on removeWaiter race
for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
s = q.next;
if (q.thread != null)
pred = q;
else if (pred != null) {
pred.next = s;
if (pred.thread == null) // check for race
continue retry;
}
else if (!UNSAFE.compareAndSwapObject(this, waitersOffset,
q, s))
continue retry;
}
break;
}
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}
}
}
而FutureTask则继承于RunnableFuture,换句话说,FutureTask也是一个实现了Runnable接口的对象
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
接下来我们调用了asyncTask.execute(1000);进入源码
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
在demo里我们传入的是1000,是一个Integer型变量,所以我们需要将AsyncTask第一个参数设置为Integer
这里出现了一个sDefaultExecutor变量,我们来看看定义
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
而serialExecutor则是AsyncTask内部一个子类
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);
}
}
}
Executor是一个线程池的接口,SerialExecutor是一个实现了Executor的线程池对象,也就是说SerialExecutor可以对线程进行管理,关于线程池又是另外的故事了。
让我们回到主线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;
}
mStatus默认值为Status.PENDING,判断过后把mStatus改为Status.RUNNING,所以当我们在第一次没完成时再点击按钮是没有用的,程序会抛出异常
程序调用ASyncTask第一个方法onPreExecute();我们在里面进行了setText,我们在主线程调用的asyncTask.execute(1000);
所以该方法运行在主线程中,更新UI没有问题
然后将我们传入的参数放入mWorker中
我们调用exec.execute(mFuture);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();
}
}
其中mTasks.offer是JAVA源码,作用是将传入的对象放入mTasks(本身就是一个队列,遵循先进先出原则)末尾
如果mActive为空,调用scheduleNext(),因为我们是第一次调用,所以mActive没有值,进入scheduleNext()
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
先给mActive赋值,mTask.poll把队列向前推一位,那就是我们刚刚放入的匿名Runnable,然后调用THREAD_POOL_EXECUTOR
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
实现代码我就不贴上来了,解释一下参数作用
CORE_POOL_SIZE:线程池的核心线程数,默认情况下,核心线程会在线程池中一直存活
MAXIMUM_POOL_SIZE:线程池所能容纳最大线程数,当活动线程达到这个数值后,后续的新任务会被阻塞。
KEEP_ALIVE:非核心线程闲置时长,超过这个时长,非核心线程就会回收。在THREAD_POOL_EXECUTOR里有一个allowCoreThreadTimeOut属性,如果把
它设置成true的话,KEEP_ALIVE对核心线程依然有效
TimeUnit.SECONDS:这个是KEEP_ALIVE的时间单位,这里选择了秒,还可以选择TimeUnit.MINUTES(分钟)等
sPoolWorkQueue:线程池中的任务队列,通过线程池的execute提交的Runnable对象会被储存在里面
sThreadFactory:线程工厂,为线程池提供创建新线程的功能。
ThreadPoolExecutor执行任务有这么几个规则
1.如果线程池中的核心线程数量未满,则启动一个核心线程来执行任务
2.如果核心线程数量已满,则任务进入任务队列中排队等待,也就是sPoolWorkQueue中
3.如果sPoolWorkQueue已满,如果线程数量未满,那么启动一个非核心线程来执行这个任务
4.如果都满了,那么拒绝执行任务。
我们来看一下AsyncTask中定义的代码
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 ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
根据上面代码,我们可以得出,在ASyncTask中
1.核心线程数=cpu核心数+1
2.线程池最大线程数=2*cpu核心数+1
3.核心线程没有超时机制,非核心线程闲置时间为1秒
4.任务队列容量为128
所以说ASyncTask是一个轻量级异步任务类
接下来继续调用
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
这就是刚才总结的线程添加规则,调用addWorker(command.true)
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
以上源码都位于java.util.concurrent.ThreadPoolExecutor中
这里解释一下,如果线程添加成功了,那就调用一个包含着Runnable的Thread.start();
我们就回到了在Runnable中重写的run方法。
我们已经知道了,FutureTask是一个实现了Runnable的子类,看看里面的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);
}
}
这段代码位于java.util.concurrent.FutureTask中
这段代码本质调用了构造时传入的Callable对象中的call方法,因此,call方法是在线程池中执行的,让我们回顾一下call方法干了什么
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));
}
};
mTaskInvoked.set(true);表示任务已经被执行过了
然后调用return postResult(doInBackground(mParams));这里才是调用doInBackground的时候,正因如此,doInBackground才会在子线程中调用
我们来看一下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的通信机制了,如果还有疑惑可以看我另一篇博客--Handler机制
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;
}
}
}
调用上面代码中的handleMessage
这里要说明一下,在demo中,doInBackground中还调用了publishProgress方法,将进度传入
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
在demo中我们传递的是for循环中i的值,于是在handlemessage中被取出传递给onProgressUpdate(Integer... values)
当循环结束的时候,返回了一个String类型的值,这个值在handlemessage中同样被取出,然后传入finsh方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
可以看到调用onPostExecute(String result)方法并将返回值传递进去,到这里ASyncTask调用就真正结束了
再多说几句,ASyncTask在1.6之前是串行执行任务,1.6-3.0时候是并行执行任务,到3.0至今又改成串行执行任务,程序员真是闲得慌
因为ASyncTask队列的特性,任务为串行执行,可是我们想并行执行怎么办呢,Android给我们提供了executeOnExecutor方法,调用这个
方法启动ASyncTask就可以串行执行了
总结一下ASyncTask
1.ASyncTask一共有两个线程池,一个叫serialExecutor,另一个叫THREAD_POOL_EXECUTOR,前者用来给任务排队,后者则是用来执行任务
2.除了doInbackground,其他方法都在主线程中执行
3.ASyncTask有一个内部Handler sHandler,在执行完DoinBackground以后用来回到主线程中
ASyncTask流程简介:
1.ASyncTask在构造函数中初始化了两个变量,WorkerRunnable和FutureTask(WorkerRunnable作为构造参数),重写WorkerRunnable的call方法和FutureTask的done方法
2.调用execute,实际上调用一个实现了Excutor接口的线程池serialExecutor中的execute方法。
3.在execute方法中,新建一个Runnable对象,将FutureTask(继承Runnable的子类).run方法加入Runnable对象并将其被压入mTask队列,然后创建新的线程池THREAD_POOL_EXECUTOR
4.取出的FutureTask被传入THREAD_POOL_EXECUTOR.execute中
5.THREAD_POOL_EXECUTOR中将FutureTask加入消息队列,然后将其用Thread包裹,并调用Thread.start方法,这个方法调用就是3新建的Runnable对象
6.调用FutureTask.run方法,run方法中调用WorkerRunnable(构造时传入).call方法,而call方法中调用了doInbackground方法
7.call方法执行完以后使用Handler机制回到主线程
8.调用剩下方法,结束