handler原理全面解析

130 阅读1分钟

最近在准备面试,一些文章会持续更新

handler消息发送流程

大致流程是

  • 发送消息: handler.sendmaeesgae->handler.enquenmessage->queue.enquenmessage

  • 接收消息: Looper.prepaer->looper.loop()->queue.next->dispatchmessage 从handler的sendmessage()开始,会调用handler的enquenmessage

    public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }

接着就会进入messagequeue的enquenmessage()。

if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

queue采用链表结构,如果delaytime为0则插入头节点,不然的话就插入链表中

一个线程有几个handler

一个

一个线程有几个looper,如何保证

一个looper,looper通过looper.prepare()来创建一个looper对象

  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));
    }

我们可以看到其最主要的是threadlocal.set()方法,然后我们进入一下threadlocal

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

可以发现threadlocal的set方法中有threadlocalmap,作为map类,可以存入key,value,而存入的key就是currentthread,至此,thread和looper已经产生了一对一的对应关系

 if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }

而这段代码,如果该threadlocal已经存在looper,就不会新建一个looper,这就保证了looper的单一性。

handler内存泄露的原因

非静态内部类持有外部引用

持续更新。。。