Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android AsyncTask 原理及Java多線程探索

Android AsyncTask 原理及Java多線程探索

編輯:關於Android編程

一 Java 線程

Thread

在Java 中最常見的起線程的方式,new Thread 然後重寫run 方法。新線程的函數執行的代碼就是run函數。

new Thread(){

    @Override
    public void run() {
        System.out.println("Time:" + System.currentTimeMillis() + " Thread:"+ Thread.currentThread().getName() + " || Hello this is Thread");
        super.run();
    }
}.start();

Runnable

第二種方式就是new Runable,看下Thread的run函數,這裡判斷了target 是否為空,target 類型為Runnable ,就是我們傳遞的參數,如果不為空,執行Runnable的Run 函數。所以在Thread中一共執行了兩個Run函數,Thread.run and Runnable.run。

new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Time:" + System.currentTimeMillis() + " Thread:" + Thread.currentThread().getName()
                        + " || Hello this is Runnable");
    }
}, "RunnableThread").start();

Thread的run函數: 
public void run() {
        if (target != null) {
            target.run();
        }
    }

Callable and FutureTask

第三種方式是Callable 方式,是Java 為了簡化並發二提供的API。看下類圖的繼承關系:
FutureTask類圖
FutureTask 繼承了 RunnableFuture 接口,而RunnableFuture接口繼承了Runnable 和Future接口。所以FutureTask 可以作為Runnable類型傳遞給Thread。同時FutureTask內部持有一個Callable類型的變量,Callable 有返回值,FutureTask和Runnable不同的是可以有返回值。

Callable callable = new Callable() {

    @Override
    public String call() throws Exception {             
        Thread.sleep(5000);
        System.out.println("Time:" + System.currentTimeMillis() + " Thread:"+ Thread.currentThread().getName() + " || Hello this is Callable");
        return "Callable";
    }
};

final FutureTask futureTask= new FutureTask(callable);
new Thread(futureTask, "FutureTaskThread").start();
try {
    String result = futureTask.get();
    System.out.println("Time:" + System.currentTimeMillis() + " Thread:"+ Thread.currentThread().getName() + " || " + result );
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

從運行日志上看,主線程在futureTask.get()阻塞等待 futureTask run 結束。

Time:1479020490215 Thread:Thread-0 || Hello this is Thread
Time:1479020490215 Thread:RunnableThread || Hello this is Runnable
Time:1479020495221 Thread:FutureTaskThread || Hello this is Callable
Time:1479020495221 Thread:main || Callable

FutureTask 重寫了Runnable的Run函數,看下代碼的實現,在FutureTask的run函數中調用了Callable 類型的call。

!UNSAFE.compareAndSwapObject(this, runnerOffset,null,Thread.currentThread())),保存Thread的句柄。這個可以通過FutureTask控制線程。 調用Callable#call函數。 set(result);保存返回結果。在調用線程中可以使用get獲取返回結果。 sun.misc.unsafe類的使用 http://blog.csdn.net/fenglibing/article/details/17138079
    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);
        }
    }

FutureTask序列圖

二 線程池

前面創建線程每次都是一個,管理起來也比較麻煩,線程池是為了避免重復的創建Thread對象,避免過多消耗資源,同時也能方便的線程的管理。主要有以下幾種類型。

固定線程池 Executors.newFixedThreadPool(); 可變線程池 Executors.newCachedThreadPool(); 單任務線程池 Executors.newSingleThreadExecutor(); 延遲線程池 Executors.newScheduledThreadPool();

線程池和Callable 結合使用:

ExecutorService pool = Executors.newFixedThreadPool(2);
Future future1 = pool.submit(callable);
Future future2 = pool.submit(callable);
try {
    String result1 = future1.get();
    System.out.println("Time:" + System.currentTimeMillis() + " Thread future1:"+ Thread.currentThread().getName() + " || " + result1);
    String result2 = future2.get();
    System.out.println("Time:" + System.currentTimeMillis() + " Thread future2:"+ Thread.currentThread().getName() + " || " + result2);

} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

Executors.newFixedThreadPool(2)的日志:
可以看出兩個線程並發執行:

Time:1479020495221 Thread:main || Callable
Time:1479020500228 Thread:pool-1-thread-1 || Hello this is Callable
Time:1479020500228 Thread:pool-1-thread-2 || Hello this is Callable
Time:1479020500229 Thread future1:main || Callable
Time:1479020500229 Thread future2:main || Callable

修改為Executors.newFixedThreadPool(1)
由於為一個線程,變成串行模式:

Time:1479020696436 Thread:main || Callable
Time:1479020701444 Thread:pool-1-thread-1 || Hello this is Callable
Time:1479020701444 Thread future1:main || Callable
Time:1479020706449 Thread:pool-1-thread-1 || Hello this is Callable
Time:1479020706450 Thread future2:main || Callable

線程池的詳細使用參考:

線程池技術

JAVA線程池的分析和使用

三 Android AsyncTask

AsyncTask 的簡單使用

AsyncTask 為一個泛型抽象類,定義如下:
public abstract class AsyncTask

new HttpPostAsyncTask(this.getApplicationContext(), code).execute(URL);

public class HttpPostAsyncTask extends AsyncTask {

    private final static String TAG = "HttpTask";
    public final String mUrl = "http://www.weather.com.cn/data/cityinfo/";

    private Context mContext;
    private String  mCode;
    public HttpPostAsyncTask(Context context, String code){
        mContext = context;
        mCode    = code;
    }

    @Override
    protected String doInBackground(String... params) {
        String httpurl = mUrl+"/"+mCode+".html";
        String strResult = null;

        try {
            HttpGet httpGet = new HttpGet(httpurl);
            Log.d(TAG, "url:"+httpurl);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(httpGet);

            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){
                Log.e(TAG, "httpResponse:"+httpResponse.toString());
                strResult = EntityUtils.toString(httpResponse.getEntity());
                WeatherProvider.insertWeatherInfo(strResult);   
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            strResult = ex.toString();
        }

        return strResult;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        WeatherProvider.insertWeatherInfo(result);
        Intent intent = new Intent(UpdateService.updateSuccessIntent);
        mContext.sendBroadcast(intent);
    }
}

AsyncTask 的原理

兩板斧

看下AsyncTask 的構造函數,(7.0代碼)在構造函數中new了WorkerRunnable, WorkerRunnable 繼承自Callable, 重新了Call函數,在Call函數中調用了doInBackground,函數,怎麼實現的新線程好像已經呼之欲出了。按照套路,mFuture = new FutureTask 並且以new的WorkerRunnable mWorker為參數。下面要做的就是把mFuture 提交給線程池。
在這裡完成了兩板斧:

mWorker = new WorkerRunnable ,在mWorker中調動doInBackground。 mFuture = new FutureTask This constructor must be invoked on the UI thread,這個是為什麼?
/**
 * 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
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                return postResult(result);
            }
        };

        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 occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

第三板斧

AsyncTask 執行的時候要調用 execute. 最終調用exec.execute(mFuture);
在上面線程池的測試中調用的是ExecutorService 的submit 接口,在這裡使用的是execute。
二者的區別是 submit 有返回值,返回值為 Future類型,這樣可以通過get接口獲取執行結果。
execute 無返回值。那如何獲取返回值。如果是submit 接口,如果多個線程執行,在主線程中只能依次獲取返回結果,而多個返回結果的次序和時間並不確定,就會造成主線程阻塞。Android 的Thread Handler 模型需要出廠了,Android 的編程思想是不是很強大,Java 的線程池技術雖然解決了線程的復用 管理問題,可是沒有解決線程的執行結果訪問的問題。在FutureTask 的run 函數中會調用set 函數保存返回結果。set函數會調用done() 函數。看下AsyncTask 的構造函數中new FutureTask的時候重新實現的done()函數。done->postResultIfNotInvoked->postResult,
在postResult中首先通過

Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
構造了通過參數為AsyncTaskResult的message 然後 Handler message.sendToTarget 通知主線程。
 public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
 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;
    }


    private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }   

結果已經有了,那怎麼處理呢.getHandler 獲取的Handler. Handler是和主線程關聯的。onProgressUpdate onPostExecute出場了,在主線程中調用。

    private static class InternalHandler extends Handler {
        public InternalHandler() {
            super(Looper.getMainLooper());
        }

        @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;
            }
        }
    }

    private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

線程池的問題

在Android 的歷史上AsyncTask 修改過多次,主要是線程的數量和並發的問題。又有CPU的核數是固定的,太多的線程反而會造成效率的地下,因此在新的版本上線程最大為:核數*2 +1。從SerialExecutor的實現看,AsyncTask 默認執行為串行。
不過Google 給我們提供了可以修改為並行的API:executeOnExecutor(Executor exec,Params… params) 自定義Executor。

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;

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();
            }
        }

主線程調用的問題

在構造函數的注釋中看到不能再非UI線程中調用AsyncTask.發做個測試,測試環境為 API 24 模擬器:

    final String code = intent.getStringExtra("citycode");
    new Thread(){

        @Override
        public void run(){
            new HttpPostAsyncTask(UpdateService.this.getApplicationContext(), code).execute("");
        }
    }.start();

No Problem. 一切正常。原因可能是和Handler 有關,在API24 版本中Handler 獲取的是主線程的Handler, 這樣在onPostExecute 執行UI操作的時候就不會有問題。在老的版本上獲取Handler 可能方式不一樣,獲取的調用線程的Handler. 沒有比較舊的代碼,手頭沒有代碼不能確認。

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