android-Message解析

一、首先解析一下该类中的重点方法与字段

1、private static final Object sPoolSync = new Object();//创建线程锁

2、private static Message sPool;//Message实例对象,用于Message的重复利用率
3、private static int sPoolSize = 0;//Message pool的数量
4、private static final int MAX_POOL_SIZE = 50;//Message pool中Message的最大数量
5、创建新的Message,这是Message提供的,所以不用咱们手动去创建新的Message,并且Message可以重复利用Message,这样大大提高了效率,减少了手机内存。

/**
 * Return a new Message instance from the global pool. Allows us to
 * avoid allocating new objects in many cases.
 */
public static Message obtain() {
    synchronized (sPoolSync) {
        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();
}
6、复制Message

/**
 * Same as {@link #obtain()}, but copies the values of an existing
 * message (including its target) into the new one.
 * @param orig Original message to copy.
 * @return A Message object from the global pool.
 */
public static Message obtain(Message orig) {
    Message m = obtain();
    m.what = orig.what;
    m.arg1 = orig.arg1;
    m.arg2 = orig.arg2;
    m.obj = orig.obj;
    m.replyTo = orig.replyTo;
    m.sendingUid = orig.sendingUid;
    if (orig.data != null) {
        m.data = new Bundle(orig.data);
    }
    m.target = orig.target;
    m.callback = orig.callback;

    return m;
}

你可能感兴趣的:(多线程)