AsyncTask是google為易用和有效的異步操作UI線程的所開發的一個封裝類。使用者可以很輕易的使用其進行后台操作,然后將結果傳給UI線程,而不需要使用Thread和Handler。
這樣好用的一個類,顯然可以在ListView異步加載圖片時大顯身手,本着這樣的想法,筆者瞬間就完成了一段這樣的模擬代碼:
Adapter的getView方法:
1 @Override 2 public View getView(int pos, View view, ViewGroup viewGroup) { 3 if (view == null) { 4 view = getLayoutInflater().inflate(R.layout.test2_list_item, 5 null); 6 } 7 ImageView imageView = (ImageView) view.findViewById(R.id.imageView); 8 //這里每次都new出一個新的AsyncTask,進行執行。 9 new TestAsyncTask(imageView, pos).execute(new Object()); 10 TextView itemView = (TextView) view.findViewById(R.id.itemView); 11 itemView.setText("測試數據" + pos); 12 return view; 13 }
TestAsyncTask:
1 private class TestAsyncTask extends AsyncTask { 2 private ImageView imageView; 3 private int index; 4 5 public TestAsyncTask(ImageView imageView, int index) { 6 this.imageView = imageView; 7 this.index = index; 8 } 9 10 @Override 11 protected Object doInBackground(Object... arg0) { 12 // 模擬長時間的運算;大多數情況下是等待進行網絡請求。 13 long sum = 0; 14 for (int i = 0; i <= 10000 * 100; i++) { 15 sum += i * 1l; 16 } 17 return null; 18 } 19 20 @Override 21 protected void onPostExecute(Object result) { 22 //模擬已經獲得了網絡請求的圖片 23 imageView.setImageBitmap(BitmapFactory.decodeResource( 24 getResources(), R.drawable.image01, null)); 25 } 26 }
運行調試,圖片一個一個全都加載出來,沒有問題,正當我瘋狂的向下翻動着,妄圖享受一下列表迅速滑動的快感的時候,一個無情的錯誤彈了出來。
04-17 11:22:52.009: E/AndroidRuntime(22792): FATAL EXCEPTION: main
04-17 11:22:52.009: E/AndroidRuntime(22792): java.util.concurrent.RejectedExecutionException: pool=128/128, queue=10/10
04-17 11:22:52.009: E/AndroidRuntime(22792): at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1961)
04-17 11:22:52.009: E/AndroidRuntime(22792): at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:794)
04-17 11:22:52.009: E/AndroidRuntime(22792): at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1315)
好吧,現在我理解為啥網絡上流傳的異步加載圖片是用更加繁瑣的Thread加Handler形式,而不用AsyncTask了。
難道是AsyncTask有什么用法上的問題,從出錯結果來看貌似是達到了某個上限被拒絕了。那我們就從這個java.util.concurrent.RejectedExecutionException錯誤入手。
翻看java的在線文檔RejectedExecutionException,我們看到了這個錯誤的解釋:
public class RejectedExecutionException
extends RuntimeException
Exception thrown by an Executor when a task cannot be accepted for execution.
Since:
1.5
See Also:
Serialized Form
這個表明是Executor這個類不接受執行task時拋出的異常。而Executor是java1.5之后增加的java.util.concurrent包中操作多線程的主要類。可以執行多個RunnableTask,看來google的AsyncTask就是用的這套API。
了解到這點,我們就可以打開AsyncTask的源碼查看它到底是怎么實現的:
打開源碼之后,找到execute方法:
1 /** 2 * Executes the task with the specified parameters. The task returns 3 * itself (this) so that the caller can keep a reference to it. 4 * 5 * This method must be invoked on the UI thread. 6 * 7 * @param params The parameters of the task. 8 * 9 * @return This instance of AsyncTask. 10 * 11 * @throws IllegalStateException If {@link #getStatus()} returns either 12 * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. 13 */ 14 public final AsyncTask<Params, Progress, Result> execute(Params... params) { 15 if (mStatus != Status.PENDING) { 16 switch (mStatus) { 17 case RUNNING: 18 throw new IllegalStateException("Cannot execute task:" 19 + " the task is already running."); 20 case FINISHED: 21 throw new IllegalStateException("Cannot execute task:" 22 + " the task has already been executed " 23 + "(a task can be executed only once)"); 24 } 25 } 26 27 mStatus = Status.RUNNING; 28 29 onPreExecute(); 30 31 mWorker.mParams = params; 32 sExecutor.execute(mFuture); 33 34 return this; 35 }
找到這里使用的Executor是sExecutor這個屬性,這樣來到它賦值的地方
1 private static final String LOG_TAG = "AsyncTask"; 2 3 private static final int CORE_POOL_SIZE = 5; 4 private static final int MAXIMUM_POOL_SIZE = 128; 5 private static final int KEEP_ALIVE = 10; 6 7 private static final BlockingQueue<Runnable> sWorkQueue = 8 new LinkedBlockingQueue<Runnable>(10); 9 10 private static final ThreadFactory sThreadFactory = new ThreadFactory() { 11 private final AtomicInteger mCount = new AtomicInteger(1); 12 13 public Thread newThread(Runnable r) { 14 return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); 15 } 16 }; 17 18 private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, 19 MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
可以看到他是構造了一個ThreadPoolExecutor常量,保證new出多個AsyncTask都是使用這一個Executor。異常應該是它拋出的,我們看下這個類的文檔,其中有一段是這樣描述的:
Rejected tasks
New tasks submitted in method execute(Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the execute method invokes the rejectedExecution(Runnable, ThreadPoolExecutor) method of its RejectedExecutionHandler. Four predefined handler policies are provided:
1.In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.
2.In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
3.In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.
4.In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)
It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.
原來在Executor的隊列和容量都達到最大時,再次增加新的task的時候將會進行拒絕行為,而默認的拒絕行為就是拋出這個RejectedExecutionException異常。
看到這里頓時恍然了,原來初始化ThreadPoolExecutor沒有指定拒絕行為,導致了異常的發生。google,你可以的!
那解決方案也就誕生了,就是復制一份AsyncTask的源碼,自己重寫這個初始化方法,增加相應的拒絕策略,后面就有幾個可供選擇的策略。修改AsyncTask源碼如下
1 private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, 2 MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory, new ThreadPoolExecutor.DiscardOldestPolicy());
再次運行,OK,不會再拋出那個異常了。
其實當你看AsyncTask的google官方文檔時,你會發現后面有這么一段:
Order of execution
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT
, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB
, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
也就是說剛開始,AsyncTask是被限制在一個線程里。從1.6開始,使用了線程池,允許運行多任務同時進行。而到了3.0之后,又被限制在一個線程里為了避免多線程執行的錯誤。
變3次了,你可以的,google。
為了驗證這段話,瞅瞅3.0之后的AsyncTask的源碼:
private static final String LOG_TAG = "AsyncTask"; private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; 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>(10); /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final InternalHandler sHandler = new InternalHandler(); //這里我們發現到了這個默認的執行器,是下面實現的線性隊列。 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); 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); } } }
這樣我們也就可以根據3.0的源碼修改我們的AsyncTask里的默認執行器,同樣使用SerialExecutor保證只會啟用一個線程。另外3.0的AsyncTask多了一個executeOnExecutor(java.util.concurrent.Executor, Object[])
方法,如果你希望有多個任務同時啟動,也可以使用
THREAD_POOL_EXECUTOR執行。
該篇文章只是淺淺的探討了一下使用AsyncTask的RejectedExecutionException問題解決,對於多線程理解多有不足之處,歡迎各位大牛拍磚。