在android中,我们会经常使用到Handler,Message,Looper和MessageQueue,因为它们之间的联系已经被封装好了,所以对于上层来说我们只知道使用Handler,Message就可以了。对于只关注应用开发而言,可以理所当然地这么认为,但是我们最好还是了解下面的运作机制。
首先我们从创建一个HandlerThread开始
在这个过程中我们需要重点了解 thread和looper是怎么绑定的?
一个thread对象只能和一个looper做绑定,在prepare()的时候做的绑定,其实就是把 thread对象和一个looper对象当作 <key,value>放到ThreadLocal (一个类似于map的数据结构) 中,这是一个静态的变量。
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
然后进入Looper.loop() 循环中,等待事件触发或者超时,jni层的looper用到了epoll ,怎么理解epoll呢?