Android AsyncTask 原理及Java多線程探索

Android AsyncTask 原理及Java多線程探索

一 Java 線程

Thread

在Java 中最常見的起線程的方式,new Thread 然后重寫run 方法碳褒。新線程的函數(shù)執(zhí)行的代碼就是run函數(shù)折砸。

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函數(shù)沙峻,這里判斷了target 是否為空睦授,target 類型為Runnable ,就是我們傳遞的參數(shù)摔寨,如果不為空去枷,執(zhí)行Runnable的Run 函數(shù)。所以在Thread中一共執(zhí)行了兩個Run函數(shù)是复,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函數(shù): 
public void run() {
        if (target != null) {
            target.run();
        }
    }

Callable and FutureTask

第三種方式是Callable 方式,是Java 為了簡化并發(fā)二提供的API淑廊《河啵看下類圖的繼承關(guān)系:


FutureTask類圖
FutureTask類圖

FutureTask 繼承了 RunnableFuture 接口,而RunnableFuture接口繼承了Runnable 和Future接口季惩。所以FutureTask 可以作為Runnable類型傳遞給Thread录粱。同時FutureTask內(nèi)部持有一個Callable類型的變量,Callable 有返回值蜀备,F(xiàn)utureTask和Runnable不同的是可以有返回值关摇。

Callable<String> callable = new Callable<String>() {

    @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<String> futureTask= new FutureTask<String>(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();
}

從運(yùn)行日志上看,主線程在futureTask.get()阻塞等待 futureTask run 結(jié)束碾阁。

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函數(shù)输虱,看下代碼的實(shí)現(xiàn),在FutureTask的run函數(shù)中調(diào)用了Callable 類型的call脂凶。

  1. !UNSAFE.compareAndSwapObject(this, runnerOffset,null,Thread.currentThread()))宪睹,保存Thread的句柄。這個可以通過FutureTask控制線程蚕钦。
  2. 調(diào)用Callable#call函數(shù)亭病。
  3. set(result);保存返回結(jié)果。在調(diào)用線程中可以使用get獲取返回結(jié)果嘶居。
  4. 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<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);
        }
    }
FutureTask序列圖
FutureTask序列圖

二 線程池

前面創(chuàng)建線程每次都是一個罪帖,管理起來也比較麻煩促煮,線程池是為了避免重復(fù)的創(chuàng)建Thread對象,避免過多消耗資源整袁,同時也能方便的線程的管理菠齿。主要有以下幾種類型。

  1. 固定線程池 Executors.newFixedThreadPool();
  2. 可變線程池 Executors.newCachedThreadPool();
  3. 單任務(wù)線程池 Executors.newSingleThreadExecutor();
  4. 延遲線程池 Executors.newScheduledThreadPool();

線程池和Callable 結(jié)合使用:

ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> future1 = pool.submit(callable);
Future<String> 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)的日志:
可以看出兩個線程并發(fā)執(zhí)行:

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

線程池的詳細(xì)使用參考:

線程池技術(shù)

JAVA線程池的分析和使用

三 Android AsyncTask

AsyncTask 的簡單使用

AsyncTask 為一個泛型抽象類绳匀,定義如下:
public abstract class AsyncTask<Params, Progress, Result>

  1. Params:表示輸入的參數(shù)類型,在execute doInBackground參數(shù)類型炸客。
  2. Progress:進(jìn)度條參數(shù)類型疾棵,publishProgress參數(shù)類型。
  3. Result:結(jié)果參數(shù)類型痹仙,onPostExecute參數(shù)類型

其中doInBackground 在后臺新的線程中調(diào)用是尔,onPostExecute在主線程中調(diào)用。使用的時候調(diào)用execute蝶溶。

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

public class HttpPostAsyncTask extends AsyncTask<String, Integer, String> {

    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 的構(gòu)造函數(shù),(7.0代碼)在構(gòu)造函數(shù)中new了WorkerRunnable嗜历, WorkerRunnable 繼承自Callable, 重新了Call函數(shù),在Call函數(shù)中調(diào)用了doInBackground,函數(shù)抖所,怎么實(shí)現(xiàn)的新線程好像已經(jīng)呼之欲出了梨州。按照套路,mFuture = new FutureTask 并且以new的WorkerRunnable mWorker為參數(shù)田轧。下面要做的就是把mFuture 提交給線程池暴匠。
在這里完成了兩板斧:

  1. mWorker = new WorkerRunnable ,在mWorker中調(diào)動doInBackground傻粘。
  2. mFuture = new FutureTask
  3. 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<Params, Result>() {
            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<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 occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

第三板斧

AsyncTask 執(zhí)行的時候要調(diào)用 execute. 最終調(diào)用exec.execute(mFuture);
在上面線程池的測試中調(diào)用的是ExecutorService 的submit 接口弦悉,在這里使用的是execute窒典。
二者的區(qū)別是 submit 有返回值,返回值為 Future類型稽莉,這樣可以通過get接口獲取執(zhí)行結(jié)果瀑志。
execute 無返回值。那如何獲取返回值污秆。如果是submit 接口劈猪,如果多個線程執(zhí)行,在主線程中只能依次獲取返回結(jié)果良拼,而多個返回結(jié)果的次序和時間并不確定战得,就會造成主線程阻塞。Android 的Thread Handler 模型需要出廠了庸推,Android 的編程思想是不是很強(qiáng)大常侦,Java 的線程池技術(shù)雖然解決了線程的復(fù)用 管理問題浇冰,可是沒有解決線程的執(zhí)行結(jié)果訪問的問題。在FutureTask 的run 函數(shù)中會調(diào)用set 函數(shù)保存返回結(jié)果聋亡。set函數(shù)會調(diào)用done() 函數(shù)湖饱。看下AsyncTask 的構(gòu)造函數(shù)中new FutureTask的時候重新實(shí)現(xiàn)的done()函數(shù)杀捻。done->postResultIfNotInvoked->postResult,
在postResult中首先通過

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

結(jié)果已經(jīng)有了蚓庭,那怎么處理呢.getHandler 獲取的Handler. Handler是和主線程關(guān)聯(lián)的致讥。onProgressUpdate onPostExecute出場了,在主線程中調(diào)用器赞。

    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 修改過多次垢袱,主要是線程的數(shù)量和并發(fā)的問題。又有CPU的核數(shù)是固定的港柜,太多的線程反而會造成效率的地下请契,因此在新的版本上線程最大為:核數(shù)*2 +1。從SerialExecutor的實(shí)現(xiàn)看夏醉,AsyncTask 默認(rèn)執(zhí)行為串行爽锥。
不過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<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();
            }
        }

主線程調(diào)用的問題

在構(gòu)造函數(shù)的注釋中看到不能再非UI線程中調(diào)用AsyncTask.發(fā)做個測試畔柔,測試環(huán)境為 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 有關(guān),在API24 版本中Handler 獲取的是主線程的Handler, 這樣在onPostExecute 執(zhí)行UI操作的時候就不會有問題靶擦。在老的版本上獲取Handler 可能方式不一樣腮考,獲取的調(diào)用線程的Handler. 沒有比較舊的代碼,手頭沒有代碼不能確認(rèn)玄捕。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末踩蔚,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子枚粘,更是在濱河造成了極大的恐慌馅闽,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赌结,死亡現(xiàn)場離奇詭異捞蛋,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)柬姚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進(jìn)店門拟杉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人量承,你說我怎么就攤上這事搬设⊙ǖ辏” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵拿穴,是天一觀的道長泣洞。 經(jīng)常有香客問我,道長默色,這世上最難降的妖魔是什么球凰? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮腿宰,結(jié)果婚禮上呕诉,老公的妹妹穿的比我還像新娘。我一直安慰自己吃度,他們只是感情好甩挫,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著椿每,像睡著了一般伊者。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上间护,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天亦渗,我揣著相機(jī)與錄音,去河邊找鬼汁尺。 笑死央碟,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的均函。 我是一名探鬼主播亿虽,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼苞也!你這毒婦竟也來了洛勉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤如迟,失蹤者是張志新(化名)和其女友劉穎收毫,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體殷勘,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡此再,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了玲销。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片输拇。...
    茶點(diǎn)故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖贤斜,靈堂內(nèi)的尸體忽然破棺而出策吠,到底是詐尸還是另有隱情逛裤,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布猴抹,位于F島的核電站带族,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蟀给。R本人自食惡果不足惜蝙砌,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望跋理。 院中可真熱鬧拍霜,春花似錦、人聲如沸薪介。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽汁政。三九已至,卻和暖如春缀旁,著一層夾襖步出監(jiān)牢的瞬間记劈,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工并巍, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留目木,地道東北人。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓懊渡,卻偏偏與公主長得像刽射,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子剃执,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容