Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android線程(二)AsyncTask(一)

android線程(二)AsyncTask(一)

編輯:關於Android編程

 

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。

在這裡同一時刻能夠運行的線程數為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() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };

        mFuture = new FutureTask(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 execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);}

 

 

 

返回了executeOnExecutor並傳進去sDefaultExecutor(默認的線程池)。先看看executeOnExecutor的源碼:

 

 public final AsyncTask 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 mTasks = new ArrayDeque();
        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 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() {
            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(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來進行下一步的處理了。

 

 

 

 

 


 

?? ?? ?? ?? ?? ?? ?? ?? ?? ??
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved