AsyncTask實現程式碼原理
Android從1.5開始引入了AsyncTask這個類,可以幫助我們解決執行緒和介面重新整理問題,主要是對Thread+Handler這樣的封裝,但在設計模式和程式碼維護方面都有不錯的表現。早在2008年時Google推出了一個示例應用叫PhotoStream來演示UI在多執行緒網路慢速I/O下的重新整理問題,裡面的執行緒構造使用的正是AsyncTask的雛形,由於內部使用Java 1.5的併發庫比普通初級Android開發者編寫的Thread+Handler穩定很多,下面我們就android.os.AsyncTask的實現
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CORE_POOL_SIZE = 5; //執行緒池數量
private static final int MAXIMUM_POOL_SIZE = 128; //執行緒池中最大執行緒數
private static final int KEEP_ALIVE = 10;
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(10); //使用併發庫的阻塞佇列初始時儲存10個Runnable物件
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());
}
};
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); //建立執行緒池
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final int MESSAGE_POST_CANCEL = 0x3;
private static final InternalHandler sHandler = new InternalHandler(); //這個是對Handler的封裝,內部處理Thread的狀態。
private final WorkerRunnable<Params, Result> mWorker; //該類對Runnable做簡單封裝
private final FutureTask<Result> mFuture; //對於併發庫而言FutureTask是最重要的,有興趣的網友可以看下JDK原始碼
private volatile Status mStatus = Status.PENDING; //儲存當前執行緒狀態
public enum Status { //列舉類記錄當前執行緒狀態
PENDING,
RUNNING,
FINISHED,
}
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() { //構造Runable物件
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //設定執行緒優先順序為後臺,這裡Android開發網提示大家低於標準執行緒優先順序
return doInBackground(mParams);
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (InterruptedException e) { //處理Thread中斷異常
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(AsyncTask.this, result)); //執行完後通過Handler通知結果
message.sendToTarget();
}
};
}
public final Status getStatus() {
return mStatus;
}
protected abstract Result doInBackground(Params... params);
protected void onPreExecute() {
}
protected void onPostExecute(Result result) {
}
protected void onProgressUpdate(Progress... values) {
}
protected void onCancelled() {
}
public final boolean isCancelled() {
return mFuture.isCancelled();
}
public final boolean cancel(boolean mayInterruptIfRunning) {
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);
}
public final AsyncTask<Params, Progress, Result> execute(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;
sExecutor.execute(mFuture);
return this;
}
protected final void publishProgress(Progress... values) { //通過Handler通知UI重新整理
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
private void finish(Result result) {
if (isCancelled()) result = null;
onPostExecute(result);
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler { //和我們的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;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}
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;
}
}
}
經過上面簡單分析, 相信大家對Android AsyncTask會有更加深刻的理解,整個AsyncTask實現基於Thread+Handler,但對於Thread使用的是Java的併發包的FutureTask具體的可以參考JDK5以後的原始碼。
相關文章
- AsyncTask實現原理
- AsyncTask 程式碼分析
- 理解 AsyncTask 原理
- DES原理及程式碼實現
- vysor原理與程式碼實現
- 從原始碼角度談談AsyncTask的使用及其原理原始碼
- UITableView的原理——探究及重新實現程式碼UIView
- AsyncTask原始碼解析原始碼
- AsyncTask實現非同步任務執行非同步
- 【整合學習】:Stacking原理以及Python程式碼實現Python
- 用程式碼探討KVC/KVO的實現原理
- 用程式碼探討 KVC/KVO 的實現原理
- 層次分析法模型原理以及程式碼實現模型
- 支援向量機(SVM)從原理到python程式碼實現Python
- 【Redis】跳躍表原理分析與基本程式碼實現(java)RedisJava
- 常見排序演算法原理及JS程式碼實現排序演算法JS
- Rainbond 對接 Istio 原理講解和程式碼實現分析AI
- 單連結串列實現原理以及具體程式碼(java)Java
- 原始碼|ThreadLocal的實現原理原始碼thread
- Promise實現原理(附原始碼)Promise原始碼
- 從微信小程式開發者工具原始碼看實現原理(二)- - 小程式技術實現微信小程式原始碼
- Python物件導向多型實現原理及程式碼例項Python物件多型
- CRC校驗原理簡介及C程式碼實現說明C程式
- MVVM雙向繫結機制的原理和程式碼實現MVVM
- Android 原始碼分析之 AsyncTask 原始碼分析Android原始碼
- 深入原始碼解析 tapable 實現原理原始碼
- HashMap 實現原理與原始碼分析HashMap原始碼
- Netty原始碼解析 -- PoolSubpage實現原理Netty原始碼
- synchronized實現原理及ReentrantLock原始碼synchronizedReentrantLock原始碼
- Netty原始碼解析 -- PoolChunk實現原理Netty原始碼
- ConcurrentHashMap 實現原理和原始碼分析HashMap原始碼
- HashMap實現原理及原始碼分析HashMap原始碼
- Tomcat程式碼實現Tomcat
- Promise 程式碼實現Promise
- OutputStreamWriter介紹&程式碼實現和InputStreamReader介紹&程式碼實現
- Locust 程式碼指令碼實現指令碼
- 將強化學習引入NLP:原理、技術和程式碼實現強化學習
- HTML程式碼混淆技術:原理、應用和實現方法詳解HTML
- UDP內網穿透和打洞原理的C語言程式碼實現UDP內網穿透C語言