Android 消息机制

目录

概述

1. Handler

1.1 构造方法

1.2 将消息传递给消息队列   Handler#enqueueMessage()

1.3  分发消息   Handler#dispatchMessage()

2. MessageQueue 

2.1 暂存消息   MessageQueue #enqueueMessage()

2.2 读取消息   MessageQueue#next()

3.Looper

3.1 Looper中的ThreadLocal和MessageQueue 

3.2Looper的构造方法

3.3 为线程创建Looper对象  Looper#prepare()

3.4 消息循环(重点) Looper#loop()

4.Message

4.1 从消息池中获取消息 Message#obtain()

4.2 回收消息 Message#recycleUnchecked()

5 .ThreadLocal

5.1 threadLocalHashCode的生成

5.2 为当前线程添加私有数据 ThreadLocal#set()

5.3 获取当前线程的私有数据 ThreadLocal#get()

5.4 获取 Thread.threadLocals属性   ThreadLocal#getMap()

6.Thread

7.ThreadLocal#ThreadLocalMap

7.1 ThreadLocalMap 的数据结构

7.2 ThreadLocalMap的构造方法

7.3 添加元素   ThreadLocalMap#set()

7.4 获取元素  ThreadLocalMap#getEntry()


概述

         Android的消息机制主要指**Handler**的运行机制,Handler的运行需要底层的**MessageQueue**和**Looper**的支撑。MessageQueue的中文翻译为“消息队列”,其内部存储在等待处理的消息,并以队列的形式对外提供插入和删除操作。虽然名字叫做消息队列,但是它却不是真正意义上的队列,它使用单向链表的结构来存储数据,并根据Message.when(处理消息的绝对时间)对其元素进行排序,保证了消息能够按照设定的时间点进行处理。Looper的可以理解为“消息循环“,它以无限循环的方式去查找消息队列中是否有新消息,一旦有新消息就进行处理,否则就一直阻塞。**ThreadLocal**主要用于读写当前线程的私有数据。ThreadLocal并不是一种数据结构,它可以被看成是读写线程私有数据的工具类。ThreadLocal主要对Thread.threadLocals属性进行读写操作。Thread.threadLocals的类型为 **ThreadLocal.ThreadLocalMap**,它才是真正的用于存储线程私有数据的一种数据结构。ThreadLocalMap的内部实际使用数组存储数据,但外部表现为MapThreadLocalMap中存储的数据只能是**ThreadLocalMap.Entry**。ThreadLocalMap.Entry是一种类似与Map的数据结构,其Key与ThrreadLocal.threadLocalHashCode以及ThreadLocalMap的size有关,Value则为实际存储的数据,在Android的消息机制中value存储的则是与当前线程相关的Looper对象。

 

  •   每个线程是能有 只能有一个Looper(参见3.1),这个Looper 存储在Thread.threadLocals内,并通过ThreadLocal进行读取。
  •  每个Looper内 都有一个MessageQueue,用于存储等待 处理的消息。‘

 


1. Handler

1.1 构造方法

构造方法一
 

//此方法为不传Looper的构造方法,使用此方法创建Handler时,需要保证当前线程已经拥有自己的Looper。
public Handler(Callback callback, boolean async) {
      //省略 .... 

       //获取与当前线程关联的Looper (从ThreadLocal的获取),如果没有,则返回null。
        mLooper = Looper.myLooper();
      //如果如果当前线程没有与之关联的Looper,将会抛异常。
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        
       //获取由Looper维护的消息队列
        mQueue = mLooper.mQueue;
        
        mCallback = callback;
        
        //mAsynchronous 默认为false
        mAsynchronous = async;
    }


构造方法二

//此方法为传Looper的构造方法,因此在调用此方法之前需要调用 Looper.prepare()在创建Looper
//此方法最主要在新建线程中创建Handler。
public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

1.2 将消息传递给消息队列   Handler#enqueueMessage()


   //Handler发送(send***或者post***)的任何消息,最终都要汇集在这里
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        //此处可以看出,那个Handler发送的Message,最终还是由那个Handler处理。
        msg.target = this;
        //mAsynchronous的用处
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
      //调用MessageQueue 的enqueueMessage()方法 将新的消息存放的MessageQueue里
        return queue.enqueueMessage(msg, uptimeMillis);
    }

1.3  分发消息   Handler#dispatchMessage()


//此方法在Looper.loop()方法中调用
//该方法有用来判断消息应该交给谁处理.
 public void dispatchMessage(Message msg) {
        //优先msg.callback.run(), msg.callback是一个Runnable
        if (msg.callback != null) { 
            handleCallback(msg);
        } else {
             //其次交给Handler的mCallback处理
            if (mCallback != null) {
               //mCallback.handleMessage(msg)返回true,表示mCallback将单独消耗性此消息,不再交给Handler处理
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //最后,可能交给Handler自己处理
            handleMessage(msg);
        }
    }

2. MessageQueue 


2.1 暂存消息   MessageQueue #enqueueMessage()


//走完这这步后,正常情况下,新消息将会被暂存到消息队列中
boolean enqueueMessage(Message msg, long when) {

        //Message的target字段不能为空
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                //如果目标线程死亡,那么将此Message回收释放
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            //mMessages表示下一个等待处理的消息,即消息队列种的第一个消息
            Message p = mMessages;
            //是否唤醒消息队列
            boolean needWake;
            //根据时间需要处理的绝对时间点将新的消息放置在消息队列的相应位置
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                // 如果消息队列没有消息或者新消息需要马上处理或者新消息需要比mMessages优先处理
                //则将新的消息放到消息队列的首节点
                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.
                //将新消息放置到消息队列的中间(末尾),这一步通常不需要唤醒消息队列,因为它并没有被阻塞。
                //由于p.target == null基本总是false,所以 needWake总是为false。
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    //当遍历到消息队列的最后节点或者找到新消息的在队列种的后继节点 p,就跳出循环
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }



2.2 读取消息   MessageQueue#next()


    Message next() {
        // Return here if the message loop has already quit and been disposed.
        // This can happen if the application tries to restart a looper after quit
        // which is not supported.
        final long ptr = mPtr;
        if (ptr == 0) {
            return null;
        }

        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
       //循环的目的是  阻塞线程,等待下一个消息到达预定的处理时间
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                //读取下一个等待处理的消息。
                Message msg = mMessages;
               //由于msg.target==null几乎总是不成立,因此,下面if代码块总是不执行的
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
               //如果等待处理的消息不为空
                if (msg != null) {
                     //如果还没有到处理消息的时间点,则继续循环
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {  
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            //将mMessages指向下一个消息
                            mMessages = msg.next;
                        }
                        //将该消息的next指向空
                        msg.next = null;
                        //将消息标记为正在处理
                        msg.markInUse();
                        //将找到的msg返回,整个next()方法执行结束
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }
        }
    }


3.Looper


3.1 Looper中的ThreadLocal和MessageQueue 


public final class Looper {
 
    //如果没有调用Looper.prepare(),那么 sThreadLocal.get()将返回 null.
    //使用static 修饰 是为了 便于线程间公用。这是由ThreadLocal.nextHashCode 是static的间接决定的。
    //静态的nextHashCode使得每个 ThreadLocal实例都有一个独一无二的threadLocalHashCode。
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    //主线程的Looper
    private static Looper sMainLooper;  // guarded by Looper.class
    //消息队列
    final MessageQueue mQueue;
    //创建Looper对象时所在的线程,即调用 prepare()所在的线程
    final Thread mThread;
    }

3.2Looper的构造方法


private Looper(boolean quitAllowed) {
       //初始化消息队列
        mQueue = new MessageQueue(quitAllowed);
        //获取当前线程
        mThread = Thread.currentThread();
    }

3.3 为线程创建Looper对象  Looper#prepare()


//两个重载的静态方法
  public static void prepare() {
        prepare(true);
    }

//此方法用为当前线程创建Looper对象,所谓的当前线程即此方法调用的线程。
//参数quitAllowed的含义为其拥有的消息队列是否可以退出,默认为true。
    private static void prepare(boolean quitAllowed) {
      //获取与当前线程相关联的Looper对象,如果当前线程已经拥有Looper,则抛出异常。
      //因为一个线程,最多只能拥有一个Looper。
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //通过ThreadLocal将Looper对象存储到线程的内部(即线程的threadLocals字段)
        sThreadLocal.set(new Looper(quitAllowed));
    }

3.4 消息循环(重点) Looper#loop()


  //loop()方法的简化版
  public static void loop() {
         //获取与当前线程关联的Looper对象,如果没有则抛出异常。
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //消息队列
        final MessageQueue queue = me.mQueue;
        //通过无限循环轮询消息队列
        for (;;) {
            //从消息队列中取出消息
            Message msg = queue.next(); // 如果还没有到达下一个被处理的消息,则阻塞。
            
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            //如果有消息,则交给其targe进行处理。
            msg.target.dispatchMessage(msg);
            //回收消息
            msg.recycleUnchecked();
        }
    }


4.Message


4.1 从消息池中获取消息 Message#obtain()


//此方法用于获取一个Message对象
//为了避免new新的对象,此方法优先从消息池中获取消息,如果消息池中没有消息,则创建一个新的Message实例
public static Message obtain() {
        //sPoolSync对象的作用仅为访问消息池时的同步锁,别无他用。
        synchronized (sPoolSync) {
            //从下面代码中可以看出 "消息池"所使用的数据结构为单向链表。
            // sPool 为消息池的头节点,sPoolSize为消息池的大小,消息池的最大容量默认为50。
            if (sPool != null) {
                //将从池中将头节点剥离出来,并将其后继节点作为新的头节点
                Message m = sPool;
                sPool = m.next;
                //将剥离出来的消息进行重置
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

4.2 回收消息 Message#recycleUnchecked()


//此方法用于将当前消息进行回收
//此方法在MessageQueue和Looper
    void recycleUnchecked() {
        //在将消息回收到消息池之前,应该将其标记为正在使用,原因 ???
        flags = FLAG_IN_USE;
        //重置其它属性
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
            //  MAX_POOL_SIZE为消息池的最大容量,默认为50
            if (sPoolSize < MAX_POOL_SIZE) {
                //将该消息放到消息池中并作为头节点
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }


5 .ThreadLocal


5.1 threadLocalHashCode的生成


   /**
    * ThreadLocal 都依赖于每个线程内部的ThreadLocalMap,包括Thread.threadLocals 和  *inheritableThreadLocals,它们都是用了线性探测法。
     * ThreadLocal 对象在ThreadLocalMap中的主要作用是充当key ,其就是threadLocalHashCode查询出来的。
     * threadLocalHashCode 只能在ThreadLocalMaps中使用,用于在同一线程中连续创建ThreadLocal 实例时引起的  *冲突,换言之,就是为了区分不同的ThreadLocal 实例。
     * threadLocalHashCode 参与了ThreadLocalMap中table数组元素索引的计算。
    */
    private final int threadLocalHashCode = nextHashCode();

    /**
     * 注释:从0开始自动累加的哈希码,
     * 
    * 1.定义成类变量(static)的原因是使得变量与类相关而不是与实例相关,保证每个ThreadLocal实例都有独一无  
    *  二的nextHashCode,进而保证了每个ThreadLocal实例都有独一无二的threadLocalHashCode 。
    *  
    * 2.使用 原子类AtomicInteger的原因是 保证对其累加操作的原子性,从而保证线程安全。
      */
    private static AtomicInteger nextHashCode =
        new AtomicInteger();

    /**
     *   0x61c88647这是一个神奇的数字。
     * 在ThreadLocal中作为一个增长量,用于生成threadLocalHashCode 。
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * 为每个TheadLocal实例生成一个独一无二的的threadLocalHashCode 。.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

5.2 为当前线程添加私有数据 ThreadLocal#set()


public void set(T value) {
       //获取当前的线程
        Thread t = Thread.currentThread();
        //读取
        ThreadLocalMap map = getMap(t);
        if (map != null)
        // 将数据添加到线程的threadLocals中
            map.set(this, value);
        else
          //如果threadLocals为空,则为线程创建新的threadLocals.
            createMap(t, value);
    }

5.3 获取当前线程的私有数据 ThreadLocal#get()


public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        //查看ThreadLocal#setInitialValue()的源码可以看出 
        //在不重写ThreadLocal#initialValue方法的前提下,setInitialValue()的返回值为null
        //有兴趣可以查看以上两个方法的源码
        return setInitialValue();
    }


5.4 获取 Thread.threadLocals属性   ThreadLocal#getMap()


//t为当前线程
 ThreadLocalMap getMap(Thread t) {
      //threadLocals中存储着线程的私有数据
        return t.threadLocals;
    }

6.Thread


 /* ThreadLocal values pertaining to this thread. This map is maintained
  * by the ThreadLocal class. 
  */
  //实际上用来存储数据
    ThreadLocal.ThreadLocalMap threadLocals = null;
    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;


7.ThreadLocal#ThreadLocalMap


7.1 ThreadLocalMap 的数据结构


    static class ThreadLocalMap {
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;
            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
        /**
         *  初始化容量,必须为2的幂次方
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         *  内部数组
         */
        private Entry[] table;

        /**
         * 数组的大小
         */
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
        private int threshold; // Default to 0
 
    }



7.2 ThreadLocalMap的构造方法


// 此方法在Looper,prepare()方法中调用
 ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
           //初始化数组,容量为16
            table = new Entry[INITIAL_CAPACITY];
            //计算第一个元素的索引
            //查看firstKey.threadLocalHashCode的计算过程,可以看出threadLocalHashCode=0
            // 0&任何数都为0,所以i=0
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            //将第一个元素放到数组中
            table[i] = new Entry(firstKey, firstValue);
            //数组大小
            size = 1;
            //重置实际容量
            setThreshold(INITIAL_CAPACITY);
        }


7.3 添加元素   ThreadLocalMap#set()


        /**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {
        
            Entry[] tab = table;
            int len = tab.length;
            
            //计算数组元素的索引
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

7.4 获取元素  ThreadLocalMap#getEntry()


 private Entry getEntry(ThreadLocal<?> key) {
            //根据ThreadLocal的实例threadLocalHashCode 和数组的长度计算元素的索引。
            int i = key.threadLocalHashCode & (table.length - 1);
            //根据索引,获取数组元素Entry 
            Entry e = table[i];
            //然后ThreadLocal实例对数据做进一步验证。
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值