Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android AsyncTask:源碼相關知識與使用注意事項

編輯:關於 Android 程式設計

知識點補充1:Callable、Future、FutureTask

Callable

Callable和Runnable類似,也是一個接口。Runnable的定義如下:

 public interface Runnable { public abstract void run(); }

Callable從Java 1.5開始提供,位於java.util.concurrent包下:

 public interface Callable { /** * 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任務執行完畢後能夠得到任務的執行結果。

Future

Future是一個接口:

 public interface Future { boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }

Future提供了三種功能:1)判斷任務是否完成;2)能夠中斷任務;3)能夠獲取任務的執行結果。由於Future只是一個接口,無法直接用來創建對象,因此才有了下面的FutureTask。

FutureTask

FutureTask類實現了RunnableFuture接口,而RunnableFuture的定義如下:

 public interface RunnableFuture extends Runnable, Future { /** * Sets this Future to the result of its computation * unless it has been cancelled. */ void run(); }

可以看出,RunnableFuture同時繼承了Runnable接口和Future接口,所以FutureTask既可以作为Runnable被線程執行,又可以作为Future得到Callable的返回值。

FutureTask提供了兩個構造器:

 public FutureTask(Callable callable) { } public FutureTask(Runnable runnable, V result) { }

實際上,FutureTask是一個任務的操作類,它並不啟動新線程,只在自身所處的線程上操作。任務的具體實現由構造FutureTask時傳入的、實現了Callable接口的對象提供,FutureTask並不知道具體任務是什麼,它只負責調度任務:

如何啟動任務:在FutureTask的run()方法(實現自Runnable.run())中,調用Callable.call()來啟動任務,call()方法中就是任務的具體實現;
如何取消任務:在cancel()中中斷執行任務的線程、記錄任務結束狀態,並調用done()來執行用戶實現的操作;
如何返回結果:如果任務還在執行,則阻塞線程(使用LockSupport.park()),直到任務結束才返回結果,用戶可通過get()方法獲取,任務結束時同樣會調用done()。

使用FutureTask的好處在於:能更輕松地管理任務,而不像Runnable那樣扔進線程後就無所作為了。

知識點補充2:Executor

Executor是任務執行者,它不關心是什麼任務,只關心如何執行任務。它是個接口,具體如何執行取決於如何實現這個接口。java.util.concurrent.Executor的註釋中提供了一個實現示例:

 class SerialExecutor implements Executor { final Queue tasks = new ArrayDeque(); final Executor executor; Runnable active; SerialExecutor(Executor executor) { this.executor = executor; } @Override public synchronized void execute(final Runnable r) { tasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (active == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((active = tasks.poll()) != null) { executor.execute(active); } } }

這個實現的含義是:嚴格按照用戶提交的順序串行執行任務(當前任務結束後再執行下一個)。Android的AsyncTask默認就採用了這種策略。當然,用戶也可以提供自己的Executor來改變AsyncTask的運行方式。

注意事項

AsyncTask提供了一種簡便的異步處理機制,但也引入了一些麻煩。一旦使用不當,很可能對性能帶來負面影響,甚至導致內存洩露。

1、如果按順序啟動20個AsyncTask,一旦其中某個任務執行時間過長,隊列中其餘的AsyncTask都會處於阻塞狀態,必須等它執行完畢後才有機會執行下一個。為了解決這種線性隊列等待問題,可以調用AsyncTask.executeOnExecutor()強制指定使用線程池並發調度任務。

2、如何才能真正取消一個AsyncTask的執行?AsyncTask提供了cancel()方法,但線程本身並不具備中止正在執行的代碼的能力。為了讓線程能更早地被銷毀,需要在doInBackground()中不斷加入判斷任務是否被取消的邏輯:

 @Override protected ArrayList doInBackground(Void... params) { if (isCancelled()) return null; for (int i = 0; i < mVideoListAdapter.getCount(); i++) { if (isCancelled()) return null; // 處理每個item } return result; }

一旦任務被成功中止,AsyncTask就不會再調用onPostExecute(),而是通過onCancelled()回調反饋任務被取消的結果。我們可以根據任務回調到哪個方法(onPostExecute還是onCancelled),來決定是正常更新UI,還是銷毀任務所占用的內存等。

3、使用AsyncTask很容易導致內存洩露。一旦把AsyncTask寫成Activity的內部類(非靜態內部類默認持有外部類的引用),就很容易因為AsyncTask生命週期的不確定,導致Activity發生洩露。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved