雖然AsyncTask現在用的很少,但是面試的時候還是會被問到,所以是時間好好研究一下AsyncTask的源碼了
首先來看一下execute方法的邏輯:
AsyncTask
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread可以看出來execute方法只能在主線程中被調用,另外execute方法會調用executeOnExecutor方法
並且傳入一個串行的線程池對象,我們看一下AsyncTask中的串行線程池是如何實現的(從AsyncTask中抽離出來)
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;//核心線程數量爲CPU數量+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) {
//ThreadFactory創建線程,mCount.getAndIncrement()的時候實現數字自增長1
//作用跟i++的作用是一樣的,不錯i++是非線程安全的,多個線程同時操作時會造成數據錯誤
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
//一個指定容量大小爲128的LinkedBlockingQueue阻塞隊列
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
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 {
//這裏有兩個疑問點需要注意一下
//1,爲什麼不直接把r offer到隊列?因爲需要在當前加入的線程執行完成後再去調用scheduleNext()方法
//所以套了一層Runnable,從而實現線程池的串行
//2.爲什麼調用r.run()而不調用r.start()?run()和start()方法同樣會執行run方法中的邏輯
//但是start()方法的run方法執行在子線程,r.run方法執行在當前線程,如果調用start方法,則會在一個子線程中再開啓一個子線程,而run不會
r.run();
} finally {
scheduleNext();
}
}
});
//第一次,需要手動調用scheduleNext()方法
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
//從隊列中取一個頭元素,不爲空則放到THREAD_POOL_EXECUTOR線程池
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
}
不多解析,註釋都寫的很清楚了,下面來看一下executeOnexecTor方法
@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一個任務實例只能執行一次,如果執行第二次將會拋出異常
該方法中會先調用onPreExecute(),然後將FutureTask對象提交任務到串行的線程池,接下來我們來看看WorkerRunnable
和FutureTask是什麼東西,WorkerRunnable是Callable接口的一個實現類,FutureTask實現了Runnable和Future接口
我們首先來看看Future接口
Future
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
Future是一個接口,他提供給了我們方法來檢測當前的任務是否已經結束,還可以等待任務結束並且拿到一個結
果,通過調用Future的get()方法可以當任務結束後返回一個結果值,如果工作沒有結束,則會阻塞當前線程,直到
任務執行完畢,我們可以通過調用cancel()方法來停止一個任務,如果任務已經停止,則cancel()方法會返回
true;如果任務已經完成或者已經停止了或者這個任務無法停止,則cancel()會返回一個false。當一個任務被成功
停止後,他無法再次執行。isDone()和isCancel()方法可以判斷當前工作是否完成和是否取消。
那麼這個Future究竟該怎麼用呢?我們看到線程池還有一個方法可以執行一個任務,那就是submit()方法
public Future<?> submit(Runnable task) {
return e.submit(task);
}
我們看到他會返回一個Future對象,這個Future對象的泛型裏還用的是一個問號“?”,問號就是說我們不知道要返回
的對象是什麼類型,那麼就返回一個null好了,因爲我們執行的是一個Runnable對象,Runnable是沒有返回值的,所
以這裏用一個問號,說明沒有返回值,那麼就返回一個null好了。
public class ExecutorDemo {
public static void main(String[] args) {
ExecutorService es = Executors.newSingleThreadExecutor();
CountRunnable work = new CountRunnable();
Future<?> future = es.submit(work);
System.out.println("任務開始於"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
for(int i=0 ; i<10 ; i++){
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("主線程"+Thread.currentThread().getName()+"仍然可以執行");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Object object = future.get();
System.out.println("任務結束於"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" result="+object);
} catch (Exception e) {
e.printStackTrace();
}
es.shutdown();
System.out.println("關閉線程池"+es.isShutdown());
}
public static class CountRunnable implements Runnable{
private int sum;
@Override
public void run() {
for(int i=1 ; i<11 ; i++){
try {
TimeUnit.MILLISECONDS.sleep(1000);
sum+=i;
System.out.println("工作線程"+Thread.currentThread().getName()+"正在執行 sum="+sum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
我們看到Future有一個get()方法,這個方法是一個阻塞方法,我們調用submit()執行一個任務的時候,會執行Runnable中的
run()方法,當run()方法沒有執行完的時候,這個工人就會歇着了,直到run()方法執行結束後,工人就會立即將結果取回並
且交給我們。我們看到返回的result=null。那既然返回null的話還有什麼意義呢??彆着急,那就要用到Callable接口了
Callable登場
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
我們看到Callable接口和Runnable接口很像,也是隻有一個方法,不過這個call()方法是有返回值的,這個返回值是一個泛型,也
就是說我們可以根據我們的需求來指定我們要返回的result的類型
public class CallableDemo {
public static void main(String[] args) throws Exception{
ExecutorService es = Executors.newSingleThreadExecutor();
Future<Number> future = es.submit(new CountCallable());
System.out.println("任務開始於"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
Number number = future.get();
System.out.println("任務結束於"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
if(future.isDone()){
System.out.println("任務執行完畢 result="+number.num);
es.shutdown();
}
}
public static class CountCallable implements Callable<Number>{
@Override
public Number call() throws Exception {
Number number = new Number();
TimeUnit.SECONDS.sleep(2);
number.setNum(10);
return number;
}
}
static class Number{
private int num;
private int getNum(){
return num;
}
private void setNum(int num){
this.num = num;
}
}
}
我們創建我們的任務(Callable)的時候,傳入了一個Number類的泛型,那麼在call()方法中就會返回這個Number類型的對象,最後在Future的get()方法中就會返回我們的Number類型的結果。
FutureTask
說完了Future和Callable,我們再來說最後一個FutureTask,Future是一個接口,他的唯一實現類就是FutureTask,其實FutureTask
的一個很好地特點是他有一個回調函數done()方法,當一個任務執行結束後,會回調這個done()方法,我們可以在done()方
法中調用FutureTask的get()方法來獲得計算的結果。爲什麼我們要在done()方法中去調用get()方法呢? 這是有原因的,我
在Android開發中,如果我在主線程去調用futureTask.get()方法時,會阻塞我的UI線程,如果在done()方法裏調用get(),則不會
阻塞我們的UI線程。
Runnable接口又實現了Runnable和Future接口,所以說FutureTask可以交給Executor執行,也可以由調用線程直接執行
FutureTask.run()方法。FutureTask的run()方法中又會調用Callable的call()方法
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);
}
}
我們可以看到run方法中其實是先執行了Callable類型的call()方法,然後再調用set()方法將call()方法的返回值賦值給一個全局變
量,在set()方法中將call()方法的返回值傳到全局變量,這樣通過get方法得到的對象就是call()方法的返回對象,最後當run方法執行完後會調用filishComplete()方法,finishComplete()方法中又會調用抽象方法done(),所以一個FutureTask實際上執行的是一個Callable
類型實例的call()方法,call()方法纔是我們的最終任務,我們寫一個例子來演示一下FutureTask
public class MainActivity extends AppCompatActivity {
FutureTask<Number> futureTask;
CountCallable countCallable;
ExecutorService es;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countCallable = new CountCallable();
futureTask = new FutureTask<Number>(countCallable){
@Override
protected void done() {
try {
Number number = futureTask.get();
Log.i("zhangqi", "任務結束於" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()) + " result=" + number.getNum());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (CancellationException e) {
Log.i("zhangqi", "任務被取消於" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
}
}
};
es = Executors.newFixedThreadPool(2);
es.execute(futureTask);
Log.i("zhangqi", "任務被開始於" + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
}
public void cancel(View view) {
futureTask.cancel(true);
}
public static class CountCallable implements Callable<Number> {
@Override
public Number call() throws Exception {
Number number = new Number();
Log.i("zhangqi","運行在"+Thread.currentThread().getName());
Thread.sleep(5000);
number.setNum(10);
return number;
}
}
static class Number {
private int num;
private int getNum() {
return num;
}
private void setNum(int num) {
this.num = num;
}
}
}<span style="font-size:14px;"></span>
好了講完了Future,Callable,FutureTask,我們回到AsyncTask的源碼,前面說了executeOnexector方法中
會將一個FutureTask實例提交到線程池中執行,而該實例是在構造方法中被實例化,我們來看看構造方法中的代碼
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的run方法中會先調用WorkerRunnable的call()方法,該方法會調用doInBackground(Params...params)方法
得到一個Result對象,再調用postResult(result),我們來看看這個方法是幹嘛的?
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
因爲是在子線程中運行,所以通過Message發送給InternalHandler,我們來看看Handler是怎麼處理該Message
@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的finish()方法
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
在該方法中調用了抽象方法onPostExecute(Result result),通過Handler實現讓該方法在主線程中執行,我們回過頭看看
FutureTask中的done方法,在run()方法會將Callable的call()的返回值通過set方法進行賦值,這樣通過get()方法可以獲取到
Result對象,如果當我們執行了cancel()方法後,FutureTask的get()方法會拋出CancellationException異常,我們捕捉這個異
常,然後在這裏來處理一些後事 =-=!
其實AsyncTask的源碼很簡單,也就這麼點,還有個publishProgress(Progress...values)方法,很簡單