本文源碼基于 Android API 26 Platform
一、 示例
首先进胯,看如下代碼用爪,請判斷輸出結(jié)果:
public class MainThreadTestActivity extends AppCompatActivity {
private static final String TAG = MainThreadTestActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_thread_test);
View view = new View(this);
view.post(new Runnable() {
@Override
public void run() {
Log.i(TAG, "[view.post] >>>> 1 ");
}
});
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Log.i(TAG, "[handler.post] >>>> 2");
}
});
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "[runOnUiThread] >>>>> 3");
}
});
new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "[runOnUiThread from thread] >>>> 4");
}
});
}
}).start();
}
}
首先預(yù)測下,輸出結(jié)果會是怎樣的呢龄减?
下面給出運(yùn)行結(jié)果:
...I/MainThreadTestActivity: [runOnUiThread] >>>>> 3
...I/MainThreadTestActivity: [handler.post] >>>> 2
...I/MainThreadTestActivity: [runOnUiThread from thread] >>>> 4
那么项钮,問題來了:
- 第一步的
View.post
為什么沒有執(zhí)行班眯? - 為什么
runOnUiThread
會執(zhí)行的比Handler.post
快希停? - 在正常情況下,
runOnUiThread
署隘、Handler.post
宠能、View.post
這三者的執(zhí)行順序又會是怎樣的呢?
下面我們分別進(jìn)行解析磁餐。
二违崇、 解析
2.1 View.post
2.1.1 View.post
不執(zhí)行問題
首先,我們來看 View.post
源碼:
//View.java
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
即:當(dāng)執(zhí)行 View.post
方法時诊霹,如果 AttachInfo
不為空羞延,則通過 AttachInfo
的 Handler
來執(zhí)行 Runnable
;否則脾还,將這個 Runnable
拋到 View
的執(zhí)行隊(duì)列 HandlerActionQueue
中伴箩。
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
mAttachInfo = info;
//...
}
也就是只有當(dāng) View
attch 到 Window
后,才會給 AttachInfo
賦值鄙漏。所以嗤谚,在 示例 里的代碼會直接走入 getRunQueue().post(action)
。我們繼續(xù)順著源碼看下去怔蚌。
在 View
里巩步,通過 HandlerActionQueue
封裝了可執(zhí)行請求隊(duì)列。官方給它的注釋是 Class used to enqueue pending work from Views when no Handler is attached.
,也就是view還沒有 Handler
來執(zhí)行后續(xù)任務(wù)(沒有attach 到 Window
上)桦踊,將所有請求入隊(duì)椅野。
// HandlerActionQueue.java
public class HandlerActionQueue {
public void removeCallbacks(Runnable action) {
synchronized (this) {
final int count = mCount;
int j = 0;
final HandlerAction[] actions = mActions;
for (int i = 0; i < count; i++) {
if (actions[i].matches(action)) {
// Remove this action by overwriting it within
// this loop or nulling it out later.
continue;
}
if (j != i) {
// At least one previous entry was removed, so
// this one needs to move to the "new" list.
actions[j] = actions[i];
}
j++;
}
// The "new" list only has j entries.
mCount = j;
// Null out any remaining entries.
for (; j < count; j++) {
actions[j] = null;
}
}
}
public void executeActions(Handler handler) {
synchronized (this) {
final HandlerAction[] actions = mActions;
for (int i = 0, count = mCount; i < count; i++) {
final HandlerAction handlerAction = actions[i];
handler.postDelayed(handlerAction.action, handlerAction.delay);
}
mActions = null;
mCount = 0;
}
}
}
而在 View
中,
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
...
// Transfer all pending runnables.
if (mRunQueue != null) {
mRunQueue.executeActions(info.mHandler);
mRunQueue = null;
}
...
}
綜上我們就可以分析出:
由于 View view = new View(this);
沒有將view attch到window上,所以執(zhí)行的 View.post
方法將可執(zhí)行請求都緩存到請求隊(duì)列里籍胯。
所以竟闪,示例 中的代碼可改為:
View view = new View(this);
rootView.addView(view);
view.post(new Runnable() {
輸出結(jié)果為:
...I/MainThreadTestActivity: [runOnUiThread] >>>>> 3
...I/MainThreadTestActivity: [handler.post] >>>> 2
...I/MainThreadTestActivity: [runOnUiThread from thread] >>>> 4
...I/MainThreadTestActivity: [view.post] >>>> 1
成功執(zhí)行 View.post
方法,修改正確芒炼。
View.post()
只有在View
attachedToWindow
的時候才會立即執(zhí)行
2.1.2 View.post
源碼解析
通過 2.1.1
節(jié)我們知道瘫怜,View.post()
只有在 View
attachedToWindow
的時候才會立即執(zhí)行 。通過執(zhí)行 ViewRootImpl
的 ViewRootHandler
執(zhí)行本刽。
2.2 runOnUiThread
//Activity.java
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
注意:
- 如果當(dāng)前線程是 主線程 , 請求會立即執(zhí)行
- 如果當(dāng)前線程不是 主線程 , 請求會發(fā)到
UI
線程的時間隊(duì)列鲸湃。
即赠涮,在非主線程調(diào)用該方法,存在線程切換的開銷暗挑。
2.3 Handler.post
需要先把請求加入到 Handler
隊(duì)列笋除,然后執(zhí)行。
三炸裆、執(zhí)行順序分析
綜上垃它,當(dāng)在主線程分別調(diào)用 View.post
、Handler.post
烹看、 runOnUiThread
, new Thread() - [runOnUiThread]
四個方法執(zhí)行順序從快到慢為:
runOnUiThread
-Handler.post
-new Thread() - [runOnUiThread]
-View.post
(符合前面驗(yàn)證結(jié)果)
分析:
-
runOnUiThread
因?yàn)楫?dāng)前執(zhí)行在UI線程
国拇,無需線程切換,直接執(zhí)行 -
Handler.post
需要將請求加入UI線程 Handler
, 多了 入隊(duì) 及 出隊(duì) 時間 -
new Thread() - [runOnUiThread]
開啟新線程惯殊,在啟動完成后將請求加入UI線程 Handler
酱吝, 多了 線程切換 、入隊(duì) 及 出隊(duì) 時間 -
View.post
需要在view attach 到 Window 后土思,通過ViewRootImpl
的ViewRootHandler
執(zhí)行請求务热。線程切換時間遠(yuǎn)小于UI渲染時間,所以執(zhí)行最慢
擴(kuò)展: 當(dāng) 示例 中代碼在 非UI線程 運(yùn)行時己儒,runOnUiThread
和 Handler.post
開銷幾乎一樣崎岂,所以執(zhí)行結(jié)果也是順序完成。
故當(dāng)在 非UI線程 分別調(diào)用 View.post
闪湾、Handler.post
冲甘、 runOnUiThread
, new Thread() - [runOnUiThread]
四個方法執(zhí)行順序從快到慢為:
Handler.post
-runOnUiThread
-new Thread() - [runOnUiThread]
-View.post
- 感謝 公眾號
巴巴巴掌
提出的發(fā)散問題 查看公眾號原文