privatestaticfinal BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128);
/** * An {@link Executor} that can be used to execute tasks in parallel. */ publicstaticfinal 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. */ publicstaticfinal Executor SERIAL_EXECUTOR = new SerialExecutor();//串行执行的线程池
privatestaticclassSerialExecutorimplementsExecutor{ final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();//线性双向队列,用来存储所有任务 Runnable mActive;//正在执行的任务
/** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ publicAsyncTask(){ mWorker = new WorkerRunnable<Params, Result>() { public Result call()throws Exception { mTaskInvoked.set(true);
publicfinal AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params){ if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: thrownew IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: thrownew 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);
returnthis; }
publicenum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, }
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) publicvoidhandleMessage(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; } } }