一:Handler线程
先上handler线程的空闲状态的线程调用栈
java层的handler线程调用栈如下
"queued-work-looper" prio=5 tid=14 Native
| group="main" sCount=1 dsCount=0 flags=1 obj=0x12e40e20 self=0x7d038cb000
| sysTid=4367 nice=-2 cgrp=default sched=0/0 handle=0x7d00d874f0
| state=S schedstat=( 1469688 13414271 8 ) utm=0 stm=0 core=0 HZ=100
| stack=0x7d00c84000-0x7d00c86000 stackSize=1041KB
| held mutexes=
kernel: (couldn't read /proc/self/task/4367/stack)
native: #00 pc 000000000006e12c /system/lib64/libc.so (offset 6e000) (__epoll_pwait+8)
native: #01 pc 0000000000013f8c /system/lib64/libutils.so (android::Looper::pollInner(int)+144)
native: #02 pc 0000000000013e60 /system/lib64/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+60)
native: #03 pc 000000000011f9c0 /system/lib64/libandroid_runtime.so (android::android_os_MessageQueue_nativePollOnce(_JNIEnv*, _jobject*, long, int)+44)
at android.os.MessageQueue.nativePollOnce(Native method)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:160)
at android.os.HandlerThread.run(HandlerThread.java:65)
native线程使用looper的空闲调用栈
"RenderThread" daemon prio=7 tid=18 Native
| group="main" sCount=1 dsCount=0 flags=1 obj=0x12f40020 self=0x7d1ac76400
| sysTid=5116 nice=-4 cgrp=default sched=0/0 handle=0x7d0409a4f0
| state=S schedstat=( 57460835 40312650 164 ) utm=3 stm=2 core=1 HZ=100
| stack=0x7d03f9f000-0x7d03fa1000 stackSize=1009KB
| held mutexes=
kernel: (couldn't read /proc/self/task/5116/stack)
native: #00 pc 000000000006e12c /system/lib64/libc.so (offset 6e000) (__epoll_pwait+8)
native: #01 pc 0000000000013f8c /system/lib64/libutils.so (android::Looper::pollInner(int)+144)
native: #02 pc 0000000000013e60 /system/lib64/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+60)
native: #03 pc 0000000000114ed8 /system/lib64/libhwui.so (android::uirenderer::renderthread::RenderThread::threadLoop()+224)
native: #04 pc 000000000000fa68 /system/lib64/libutils.so (android::Thread::_threadLoop(void*)+280)
native: #05 pc 0000000000081a08 /system/lib64/libc.so (offset 70000) (__pthread_start(void*)+36)
native: #06 pc 00000000000234cc /system/lib64/libc.so (offset 23000) (__start_thread+68)
(no managed stack frames)
从上面两个空闲调用栈可以看出,Handler线程的关键是looper,looper的关键操作是系统调用epoll_wait,这个系统用调用使得当前线程可以陷入内核中,等待内核的事件通知。
当我们向MessageQueue中添加一条事件后,会通过native调用到Looper.cpp的wake函数,向对应的fd发起write操作,借用内核的能力唤醒对应处于在epoll_wait状态的线程
PS:looper并不需要和handler强绑定,但Handler需要和looper强绑定。