轉載請注明出處:http://blog.csdn.net/singwhatiwanna/article/details/17596225
什麼是asynctask,相信搞過android開發的朋友們都不陌生。asynctask内部封裝了thread和handler,可以讓我們在背景進行計算并且把計算的結果及時更新到ui上,而這些正是thread+handler所做的事情,沒錯,asynctask的作用就是簡化thread+handler,讓我們能夠通過更少的代碼來完成一樣的功能,這裡,我要說明的是:asynctask隻是簡化thread+handler而不是替代,實際上它也替代不了。同時,asynctask從最開始到現在已經經過了幾次代碼修改,任務的執行邏輯慢慢地發生了改變,并不是大家所想象的那樣:asynctask是完全并行執行的就像多個線程一樣,其實不是的,是以用asynctask的時候還是要注意,下面會一一說明。另外本文主要是分析asynctask的源代碼以及使用時候的一些注意事項,如果你還不熟悉asynctask,請先閱讀android之asynctask 來了解其基本用法。
這裡先給出asynctask的一個例子:
[java] view
plaincopy
private class downloadfilestask extends asynctask<url, integer, long> {
protected long doinbackground(url... urls) {
int count = urls.length;
long totalsize = 0;
for (int i = 0; i < count; i++) {
totalsize += downloader.downloadfile(urls[i]);
publishprogress((int) ((i / (float) count) * 100));
// escape early if cancel() is called
if (iscancelled()) break;
}
return totalsize;
}
protected void onprogressupdate(integer... progress) {
setprogresspercent(progress[0]);
protected void onpostexecute(long result) {
showdialog("downloaded " + result + " bytes");
}
asynctask的類必須在ui線程加載(從4.1開始系統會幫我們自動完成)
asynctask對象必須在ui線程建立
execute方法必須在ui線程調用
不要在你的程式中去直接調用onpreexecute(), onpostexecute, doinbackground, onprogressupdate方法
一個asynctask對象隻能執行一次,即隻能調用一次execute方法,否則會報運作時異常
asynctask不是被設計為處理耗時操作的,耗時上限為幾秒鐘,如果要做長耗時操作,強烈建議你使用executor,threadpoolexecutor以及futuretask
在1.6之前,asynctask是串行執行任務的,1.6的時候asynctask開始采用線程池裡處理并行任務,但是從3.0開始,為了避免asynctask所帶來的并發錯誤,asynctask又采用一個線程來串行執行任務
給大家做一下實驗,請看如下實驗代碼:代碼很簡單,就是點選按鈕的時候同時執行5個asynctask,每個asynctask休眠3s,同時把每個asynctask執行結束的時間列印出來,這樣我們就能觀察出到底是串行執行還是并行執行。
@override
public void onclick(view v) {
if (v == mbutton) {
new myasynctask("asynctask#1").execute("");
new myasynctask("asynctask#2").execute("");
new myasynctask("asynctask#3").execute("");
new myasynctask("asynctask#4").execute("");
new myasynctask("asynctask#5").execute("");
}
}
private static class myasynctask extends asynctask<string, integer, string> {
private string mname = "asynctask";
public myasynctask(string name) {
super();
mname = name;
@override
protected string doinbackground(string... params) {
try {
thread.sleep(3000);
} catch (interruptedexception e) {
e.printstacktrace();
}
return mname;
protected void onpostexecute(string result) {
super.onpostexecute(result);
simpledateformat df = new simpledateformat("yyyy-mm-dd hh:mm:ss");
log.e(tag, result + "execute finish at " + df.format(new date()));
我找了2個手機,系統分别是4.1.1和2.3.3,按照我前面的描述,asynctask在4.1.1應該是串行的,在2.3.3應該是并行的,到底是不是這樣呢?請看log
android 4.1.1上執行:從下面log可以看出,5個asynctask共耗時15s且時間間隔為3s,很顯然是串行執行的
android 2.3.3上執行:從下面log可以看出,5個asynctask的結束時間是一樣的,很顯然是并行執行
結論:從上面的兩個log可以看出,我前面的描述是完全正确的。下面請看源碼,讓我們去了解下其中的原理。
/*
* copyright (c) 2008 the android open source project
*
* licensed under the apache license, version 2.0 (the "license");
* you may not use this file except in compliance with the license.
* you may obtain a copy of the license at
* http://www.apache.org/licenses/license-2.0
* unless required by applicable law or agreed to in writing, software
* distributed under the license is distributed on an "as is" basis,
* without warranties or conditions of any kind, either express or implied.
* see the license for the specific language governing permissions and
* limitations under the license.
*/
package android.os;
import java.util.arraydeque;
import java.util.concurrent.blockingqueue;
import java.util.concurrent.callable;
import java.util.concurrent.cancellationexception;
import java.util.concurrent.executor;
import java.util.concurrent.executionexception;
import java.util.concurrent.futuretask;
import java.util.concurrent.linkedblockingqueue;
import java.util.concurrent.threadfactory;
import java.util.concurrent.threadpoolexecutor;
import java.util.concurrent.timeunit;
import java.util.concurrent.timeoutexception;
import java.util.concurrent.atomic.atomicboolean;
import java.util.concurrent.atomic.atomicinteger;
public abstract class asynctask<params, progress, result> {
private static final string log_tag = "asynctask";
//擷取目前的cpu核心數
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;
//threadfactory 線程工廠,通過工廠方法newthread來擷取新線程
private static final threadfactory sthreadfactory = new threadfactory() {
//原子整數,可以在超高并發下正常工作
private final atomicinteger mcount = new atomicinteger(1);
public thread newthread(runnable r) {
return new thread(r, "asynctask #" + mcount.getandincrement());
};
//靜态阻塞式隊列,用來存放待執行的任務,初始容量:128個
private static final blockingqueue<runnable> spoolworkqueue =
new linkedblockingqueue<runnable>(128);
/**
* 靜态并發線程池,可以用來并行執行任務,盡管從3.0開始,asynctask預設是串行執行任務
* 但是我們仍然能構造出并行的asynctask
*/
public static final executor thread_pool_executor
= new threadpoolexecutor(core_pool_size, maximum_pool_size, keep_alive,
timeunit.seconds, spoolworkqueue, sthreadfactory);
* 靜态串行任務執行器,其内部實作了串行控制,
* 循環的取出一個個任務交給上述的并發線程池去執行
public static final executor serial_executor = new serialexecutor();
//消息類型:發送結果
private static final int message_post_result = 0x1;
//消息類型:更新進度
private static final int message_post_progress = 0x2;
/**靜态handler,用來發送上述兩種通知,采用ui線程的looper來處理消息
* 這就是為什麼asynctask必須在ui線程調用,因為子線程
* 預設沒有looper無法建立下面的handler,程式會直接crash
private static final internalhandler shandler = new internalhandler();
//預設任務執行器,被指派為串行任務執行器,就是它,asynctask變成串行的了
private static volatile executor sdefaultexecutor = serial_executor;
//如下兩個變量我們先不要深究,不影響我們對整體邏輯的了解
private final workerrunnable<params, result> mworker;
private final futuretask<result> mfuture;
//任務的狀态 預設為挂起,即等待執行,其類型辨別為易變的(volatile)
private volatile status mstatus = status.pending;
//原子布爾型,支援高并發通路,辨別任務是否被取消
private final atomicboolean mcancelled = new atomicboolean();
//原子布爾型,支援高并發通路,辨別任務是否被執行過
private final atomicboolean mtaskinvoked = new atomicboolean();
/*串行執行器的實作,我們要好好看看,它是怎麼把并行轉為串行的
*目前我們需要知道,asynctask.execute(params ...)實際上會調用
*serialexecutor的execute方法,這一點後面再說明。也就是說:當你的asynctask執行的時候,
*首先你的task會被加入到任務隊列,然後排隊,一個個執行
private static class serialexecutor implements executor {
//線性雙向隊列,用來存儲所有的asynctask任務
final arraydeque<runnable> mtasks = new arraydeque<runnable>();
//目前正在執行的asynctask任務
runnable mactive;
public synchronized void execute(final runnable r) {
//将新的asynctask任務加入到雙向隊列中
mtasks.offer(new runnable() {
public void run() {
try {
//執行asynctask任務
r.run();
} finally {
//目前asynctask任務執行完畢後,進行下一輪執行,如果還有未執行任務的話
//這一點很明顯展現了asynctask是串行執行任務的,總是一個任務執行完畢才會執行下一個任務
schedulenext();
}
}
});
//如果目前沒有任務在執行,直接進入執行邏輯
if (mactive == null) {
schedulenext();
}
protected synchronized void schedulenext() {
//從任務隊列中取出隊列頭部的任務,如果有就交給并發線程池去執行
if ((mactive = mtasks.poll()) != null) {
thread_pool_executor.execute(mactive);
* 任務的三種狀态
public enum status {
/**
* 任務等待執行
*/
pending,
* 任務正在執行
running,
* 任務已經執行結束
finished,
/** 隐藏api:在ui線程中調用,用來初始化handler */
public static void init() {
shandler.getlooper();
/** 隐藏api:為asynctask設定預設執行器 */
public static void setdefaultexecutor(executor exec) {
sdefaultexecutor = exec;
* 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);
private void postresultifnotinvoked(result result) {
final boolean wastaskinvoked = mtaskinvoked.get();
if (!wastaskinvoked) {
postresult(result);
//doinbackground執行完畢,發送消息
private result postresult(result result) {
@suppresswarnings("unchecked")
message message = shandler.obtainmessage(message_post_result,
new asynctaskresult<result>(this, result));
message.sendtotarget();
return result;
* 傳回任務的狀态
public final status getstatus() {
return mstatus;
* 這個方法是我們必須要重寫的,用來做背景計算
* 所線上程:背景線程
protected abstract result doinbackground(params... params);
* 在doinbackground之前調用,用來做初始化工作
* 所線上程:ui線程
protected void onpreexecute() {
* 在doinbackground之後調用,用來接受背景計算結果更新ui
protected void onpostexecute(result result) {
* runs on the ui thread after {@link #publishprogress} is invoked.
/**
* 在publishprogress之後調用,用來更新計算進度
protected void onprogressupdate(progress... values) {
* cancel被調用并且doinbackground執行結束,會調用oncancelled,表示任務被取消
* 這個時候onpostexecute不會再被調用,二者是互斥的,分别表示任務取消和任務執行完成
@suppresswarnings({"unusedparameters"})
protected void oncancelled(result result) {
oncancelled();
}
protected void oncancelled() {
public final boolean iscancelled() {
return mcancelled.get();
public final boolean cancel(boolean mayinterruptifrunning) {
mcancelled.set(true);
return mfuture.cancel(mayinterruptifrunning);
public final result get() throws interruptedexception, executionexception {
return mfuture.get();
public final result get(long timeout, timeunit unit) throws interruptedexception,
executionexception, timeoutexception {
return mfuture.get(timeout, unit);
* 這個方法如何執行和系統版本有關,在asynctask的使用規則裡已經說明,如果你真的想使用并行asynctask,
* 也是可以的,隻要稍作修改
* 必須在ui線程調用此方法
public final asynctask<params, progress, result> execute(params... params) {
//串行執行
return executeonexecutor(sdefaultexecutor, params);
//如果我們想并行執行,這樣改就行了,當然這個方法我們沒法改
//return executeonexecutor(thread_pool_executor, params);
* 通過這個方法我們可以自定義asynctask的執行方式,串行or并行,甚至可以采用自己的executor
* 為了實作并行,我們可以在外部這麼用asynctask:
* asynctask.executeonexecutor(asynctask.thread_pool_executor, params... 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:
+ " the task has already been executed "
+ "(a task can be executed only once)");
mstatus = status.running;
//這裡#onpreexecute會最先執行
onpreexecute();
mworker.mparams = params;
//然後背景計算#doinbackground才真正開始
exec.execute(mfuture);
//接着會有#onprogressupdate被調用,最後是#onpostexecute
return this;
* 這是asynctask提供的一個靜态方法,友善我們直接執行一個runnable
public static void execute(runnable runnable) {
sdefaultexecutor.execute(runnable);
* 列印背景計算進度,onprogressupdate會被調用
protected final void publishprogress(progress... values) {
if (!iscancelled()) {
shandler.obtainmessage(message_post_progress,
new asynctaskresult<progress>(this, values)).sendtotarget();
//任務結束的時候會進行判斷,如果任務沒有被取消,則onpostexecute會被調用
private void finish(result result) {
if (iscancelled()) {
oncancelled(result);
} else {
onpostexecute(result);
mstatus = status.finished;
//asynctask内部handler,用來發送背景計算進度更新消息和計算完成消息
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);
private static abstract class workerrunnable<params, result> implements callable<result> {
params[] mparams;
@suppresswarnings({"rawuseofparameterizedtype"})
private static class asynctaskresult<data> {
final asynctask mtask;
final data[] mdata;
asynctaskresult(asynctask task, data... data) {
mtask = task;
mdata = data;
通過上面的源碼分析,我已經給出了在3.0以上系統中讓asynctask并行執行的方法,現在,讓我們來試一試,代碼還是之前采用的測試代碼,我們要稍作修改,調用asynctask的executeonexecutor方法而不是execute,請看:
@targetapi(build.version_codes.honeycomb)
new myasynctask("asynctask#1").executeonexecutor(asynctask.thread_pool_executor,"");
new myasynctask("asynctask#2").executeonexecutor(asynctask.thread_pool_executor,"");
new myasynctask("asynctask#3").executeonexecutor(asynctask.thread_pool_executor,"");
new myasynctask("asynctask#4").executeonexecutor(asynctask.thread_pool_executor,"");
new myasynctask("asynctask#5").executeonexecutor(asynctask.thread_pool_executor,"");
下面是系統為4.1.1手機列印出的log:很顯然,我們的目的達到了,成功的讓asynctask在4.1.1的手機上并行起來了,很高興吧!希望這篇文章對你有用。