<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                轉載請注明出處:[](http://blog.csdn.net/guolin_blog/article/details/42238633)[http://blog.csdn.net/itachi85/article/details/45041923](http://blog.csdn.net/itachi85/article/details/45041923) AsyncTask的基本用法這里就不在贅述了,是個安卓開發者就會。 **1.android 3.0以前的 AsyncTask** ~~~ private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final it KEEP_ALIVE = 10; …… private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); ~~~ 在這里我們又看到了ThreadPoolExecutor,它的原理我已經在上一篇介紹過了[http://blog.csdn.net/itachi85/article/details/44874511](http://blog.csdn.net/itachi85/article/details/44874511)。 在這里同一時刻能夠運行的線程數為5個,線程池總大小為128,當線程數大于核心時,終止前多余的空閑線程等待新任務的最長時間為10秒。在3.0之前的AsyncTask可以同時有5個任務在執行,而3.0之后的AsyncTask同時只能有1個任務在執行。 **2.讓我們來看看android 4.3版本的 AsyncTask** 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); } } }; } ~~~ 這段代碼初始化了兩個變量,mWorker和mFuture,并在初始化mFuture的時候將mWorker作為參數傳入。mWorker是一個Callable對象,mFuture是一個FutureTask對象,這兩個變量會暫時保存在內存中,稍后才會用到它們。 我們要運用AsyncTask時,大多時候會調用execute()方法,來看看execute()的源碼: ~~~ public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params);} ~~~ 返回了executeOnExecutor并傳進去sDefaultExecutor(默認的線程池)。先看看executeOnExecutor的源碼: ~~~ 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; } ~~~ 傳入的線程池exec調用了execute方法并將上文提到的mFuture傳了進去。 這個傳進來的線程池sDefaultExecutor就是默認的線程池SerialExecutor也就是調用了SerialExecutor的execute()方法: ~~~ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; ~~~ SerialExecutor的源碼: ~~~ 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); } } } ~~~ 調用SerialExecutor的execute方法這里可以看到傳進來一個Runnable,這個Runnable就是上文提到的mFuture(FutureTask),第九行執行了FutureTask的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); } } ~~~ 在run方法中執行了c.call,這里的c就是我們上文提到的mWorker(WorkerRunnable)。執行WorkerRunnable的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)); } ~~~ 最后一行postResult()方法源碼: ~~~ private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } ~~~ 我們發現就是發送了一個消息,上面的代碼發送的消息由這里接受: ~~~ private static class InternalHandler extends Handler { @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; } } } ~~~ 消息是MESSAGE_POST_RESULT所以會執行 result.mTask.finish(result.mData[0])? ,finish源碼: ~~~ private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } ~~~ 當被取消時會執行 onCancelled(result);否則就會調用 onPostExecute(result);這樣我們就可以在onPostExecute方發中得到我們需要的結果result來進行下一步的處理了。 **3.AsyncTask中的線程池?** AsyncTask中一共定義了兩個線程池一個是此前我們已經介紹了線程池SerialExecutor,這個是目前我們調用AsyncTask.execute()方法默認使用的線程池,這個在前一篇文章中已經講到過了,另一個是3.0版本之前的默認線程池THREAD_POOL_EXECUTOR。現在我們來回顧一下SerialExecutor的源碼: ~~~ 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(); } } ~~~ 這個默認的線程池同一時間只能處理一個任務,一個任務完成以后才可以執行下一個任務,相當于Executors.newSingleThreadPool()。上面的arrayDeque是一個裝載Runnable的隊列,如果我們一次性啟動了很多個任務,在第一次運行execute()方法的時候會調用ArrayDeque的offer()方法將傳入的Runnable對象添加到隊列的尾部, 然后判斷mActive對象是不是等于null,第一次運行等于null,于是調用scheduleNext()方法。另外在finally中也調用了scheduleNext()方法,這樣保證每次當一個任務執行完畢后,下一個任務才會執行。我們來看看scheduleNext()方法的源碼: ~~~ protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } ~~~ 首先從runnable隊列的頭部取值,如果不為空就賦值給mActive對象,然后調用THREAD_POOL_EXECUTOR去執行取出的Runnable對象。THREAD_POOL_EXECUTOR源碼: ~~~ private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final int KEEP_ALIVE = 1; . public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); ~~~ 這是3.0版本之前的線程池,同一時刻能夠運行的線程數為5個,workQueue總大小為128。當我們啟動10個任務,只有5個任務能夠優先執行,其余的任務放在workQueue中,當workQueue大于128時就會調用RejectedExecutionHandler來做拒絕處理。當然在3.0之前是并沒有SerialExecutor這個類的。如果不希望用默認線程池我們也可以使用這個3.0版本之前的線程池 ~~~ AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null); ~~~ 同時3.0版本也提供了executeOnExecutor這個方法可以傳入AsyncTask定義的線程池也可以傳入Executor定義的4種線程池,不知道這四種線程池的可以看[http://blog.csdn.net/itachi85/article/details/44874511](http://blog.csdn.net/itachi85/article/details/44874511) 傳入CachedThreadPool: ~~~ LikeListTask mLikeListTask=new LikeListTask(); executeOnExecutor(Executors.newCachedThreadPool(), null); ~~~ 當然我們也可以傳入自定義的線程池: ~~~ Executor exec =new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); new LikeListTask().executeOnExecutor(exec, null); ~~~ 我們看到這里定義的是一個類似于CachedThreadPool的一個線程池
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看