AsyncTask原始碼分析

2021-07-24 18:33:18 字數 4603 閱讀 7480

就從asynctask的構造方法開始分析

/*** creates a new asynchronous task. this constructor must be invoked on the ui thread.

*/public asynctask()

};mfuture = new futuretask(mworker) catch (interruptedexception e) catch (executionexception e) catch (cancellationexception e) }};

}可以看到在構造方法中例項化了2個成員變數mworker、mfuture。

其中workerrunnable為靜態內部類,其類宣告如下:

private static abstract class workerrunnableimplements callable

介面callable的類宣告:

public inte***ce callable

runnable 與 callable的區別:1. 是否返回結果; 2. 是否丟擲執行時異常。

futuretask的類宣告:

public class futuretaskimplements runnablefuture

其實現的介面runnablefuture的宣告:

public inte***ce runnablefutureextends runnable, future

public inte***ce runnable .

*/public void run();

}public inte***ce future

開始執行非同步任務:new asynctask(this).execute();

@mainthread

public final asynctaskexecute(params... params)

@mainthread

public final asynctaskexecuteonexecutor(executor exec,

params... params)

}mstatus = status.running;

onpreexecute();

mworker.mparams = params;

exec.execute(mfuture);

return this;}

sdefaultexecutor的定義和例項化:

public static final executor serial_executor = new serialexecutor(); // 

private static volatile executorsdefaultexecutor= serial_executor;

private static internalhandler shandler;

private final workerrunnablemworker;

private final futuretaskmfuture;

private volatile status mstatus = status.pending;

private static class serialexecutor implements executor finally

}});

if (mactive == null)

}protected synchronized void schedulenext() }}

繼續**的呼叫:

會執行語句thread_pool_executor.execute(mactive); 

public static final executor thread_pool_executor

= new threadpoolexecutor(core_pool_size, maximum_pool_size, keep_alive,

timeunit.seconds, spoolworkqueue, sthreadfactory);

threadpoolexecutor的

public void execute(runnable command)

if (isrunning(c) && workqueue.offer(command))

else if (!addworker(command, false))

reject(command);

}addworker(null, false)的函式簽名:

private boolean addworker(runnable firsttask, boolean core)

}boolean workerstarted = false;

boolean workeradded = false;

worker w = null;

try

} finally

if (workeradded)

}} finally

return workerstarted;}

內部類worker的宣告:

private final class worker

extends abstractqueuedsynchronizer

implements runnable

/** delegates main run loop to outer runworker. */

public void run()

// lock methods

//// the value 0 represents the unlocked state.

// the value 1 represents the locked state.

protected boolean isheldexclusively()

protected boolean tryacquire(int unused)

return false;

}protected boolean tryrelease(int unused)

public void lock()        

public boolean trylock()  

public void unlock()      

public boolean islocked()

void interruptifstarted() catch (securityexception ignore) }}

} final void runworker(worker w) catch (runtimeexception x) catch (error x) catch (throwable x) finally

} finally

}completedabruptly = false;

} finally }

其中的task就是asynctask的成員屬性mfuture

原始碼是基於android7.0的

-> asynctask#550#execute() -> 588 -> 226#serialexecutor#execute(mfuture) 

-> threadpoolexecutor#1303#execute(mfuture) -> 865$addworker(mfuture) 

-> threadpoolexecutor#559#worker -> 587#run() -> 1091#runworker(worker) -> 1113#task.run();

-> asynctask#301 -> public void run()的237行 -> asynctask#290

執行asynctask的mfuture的run()

futuretask 

public void run() catch (throwable ex)

if (ran)

set(result);

}} finally }

上面的c就是asynctask的屬性mworker屬性。

mworker = new workerrunnable() };

private result postresult(result result)

private static class internalhandler extends handler

@suppresswarnings()

@override

public void handlemessage(message msg) }}

如果是message_post_result分支;就執行asynctask的如下語句

private void finish(result result) else

mstatus = status.finished;}

其中更新進度的方法是後台執行緒doinbackground()方法中執行publishprogress(mcount);時呼叫父類的

@workerthread

protected final void publishprogress(progress... values) }

如果是message_post_progress分支就會呼叫onprogressupdate(),子類可以重寫該方法實現進度更新操作。

AsyncTask 原始碼分析

asynctask 內部實現原理主要是兩個執行緒池和乙個handler。兩個執行緒池分別為serialexecutor和threadpoolexecutor。其中serialexecutor是維護乙個有序佇列 threadpoolexecutor是執行任務的執行緒池。handler是internal...

7 0 AsyncTask原始碼分析

之前開發中經常使用asynctask進行非同步資料獲取,當時只限於使用,只知道大體的就是通過執行緒池 handler實現的封裝,具體的 細節沒有仔細看過,今天就閱讀一下原始碼,當作筆記。加深記憶 public asynctask mfuture new futuretask mworker catc...

AsyncTask非同步任務機制原始碼分析

建立乙個自定義列表 如何建立乙個註腳 注釋也是必不可少的 katex數學公式 新的甘特圖功能,豐富你的文章 uml 圖表 flowchart流程圖 匯出與匯入 你好!這是你第一次使用markdown編輯器所展示的歡迎頁。如果你想學習如何使用markdown編輯器,可以仔細閱讀這篇文章,了解一下mar...