Android知识Android开发Android技术知识

Android 消息机制(Handler Looper Mess

2017-07-18  本文已影响240人  GordenNee

1.概述

​ Android的消息机制主要是指Hanlder的运行机制及其附带的MessageQueue和Looper的工作过程。三者作为一个整体来实现消息机制。

2.原理概述

​ Handler的使用方法大致如下:

private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mTestTV.setText("This is handleMessage");//更新UI
                    break;
            }
        }
    };
    
  
new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);//在子线程有一段耗时操作,比如请求网络
                    mHandler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

3.ThreadLocal工作原理

3.1 ThreadLocal的使用场景

​ 早在JDK 1.2的版本中就提供java.lang.ThreadLocalThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序。

当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

ThreadLocal是一个线程内部的数据存储类,通过它可以在指定线程中存储数据,数据存储以后只可以在当前线程中获取到存储的数据,对于其他线程来说是无法获取到的。

主要的应用场景是:

3.2 ThreadLocal的使用方法

private ThreadLoacl<Boolean> mBooleanThreadLocal = new ThreadLocal<Boolean>;

mBooleanThreadLocal.set(true);
Log.d(TAG,"[ThreadMain] mBooleanThreadLocal = :" + mBooleanThreadLocal.get());

new Thread("Thread#1") {
  @Override
  public void run () {
    mBooleanThreadLocal.set(false);
    Log.d(TAG,"[Thread#1] mBooleanThreadLocal = :" + mBooleanThreadLocal.get());
  }
}

new Thread("Thread#2") {
  @Override
  public void run () {
    Log.d(TAG,"[Thread#2] mBooleanThreadLocal = :" + mBooleanThreadLocal.get());
  }
}

运行结果:

[ThreadMain] mBooleanThreadLocal = : true
[Thread#1] mBooleanThreadLocal = : false
[Thread#2] mBooleanThreadLocal = : null

​ 没有为ThreadLocal设置的情况下默认get()到的会是null。

3.3 ThreadLocal原理

​ ThreadLocal 是一个泛型类,定义为 public class ThreadLocal<T>

​ 在Java源码中有一个ThreadLocal.java,在Android源码中也有一个ThreadLocal.java。两者的主要区别在于他内部的实现方式不同。

3.3.1 java中的ThreadLocal

​ ThreadLocal是如何做到为每一个线程维护变量的副本的呢?其实实现的思路很简单:在ThreadLocal类中有一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值对应线程的变量副本。

​ ThreadLocal的set方法:

ThreadLocal.java

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

​ 在set方法中首先获取到当前Thread的对象。然后去获取ThreadLocalMap,这个ThreadLocalMap它是在每一个Thread中都有一份,可以看下getMap(t).

ThreadLocalMap getMap(Thread t) {
  return t.threadLocals;
}

​ 代码很简单就是返回当前线程中的threadLocals 对象。可以看下Thread.java中的定义。

/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

​ 接着看set()方法,如果得到的map不为空就会把当前的ThreadLocal本身作为Key值,需要保存的value值作为Value

​ 到这里可以大致理解如下:在每一个Thread中都维护一个ThreadLocalMap,这个ThreadLocalMap 的Key为ThreadLocal对象,Value为保存的值,这样一个线程中就存了多个ThreadLocal对应的值。

​ 如果得到的ThreadLocalMap为空,就去createMap,实现如下:

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

​ 可以看下ThreadLocalMap的构造方法:

ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
    table = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}

​ 通过变量命名及实现,可以知道这个构造方法就是一个初始化并put一个键值对。

​ 然后网上就传言,ThreadLocal会引发内存泄露,他们的理由是这样的:
如上图,ThreadLocalMap使用ThreadLocal的弱引用作为key,如果一个ThreadLocal没有外部强引用引用他,那么系统gc的时候,这个ThreadLocal势必会被回收,这样一来,ThreadLocalMap中就会出现key为null的Entry,就没有办法访问这些key为null的Entry的value,如果当前线程再迟迟不结束的话,这些key为null的Entry的value就会一直存在一条强引用链:
Thread Ref -> Thread -> ThreaLocalMap -> Entry -> value
永远无法回收,造成内存泄露。

​ 首先从ThreadLocal的直接索引位置(通过ThreadLocal.threadLocalHashCode & (len-1)运算得到)获取Entry e,如果e不为null并且key相同则返回e;
​ 如果e为null或者key不一致则向下一个位置查询,如果下一个位置的key和当前需要查询的key相等,则返回对应的Entry,否则,如果key值为null,则擦除该位置的Entry,否则继续向下一个位置查询
​ 在这个过程中遇到的key为null的Entry都会被擦除,那么Entry内的value也就没有强引用链,自然会被回收。仔细研究代码可以发现,set操作也有类似的思想,将key为null的这些Entry都删除,防止内存泄露。
​ 但是光这样还是不够的,上面的设计思路依赖一个前提条件:要调用ThreadLocalMap的getEntry函数或者set函数。这当然是不可能任何情况都成立的,所以很多情况下需要使用者手动调用ThreadLocal的remove函数,手动删除不再需要的ThreadLocal,防止内存泄露。所以JDK建议将ThreadLocal变量定义成private static的,这样的话ThreadLocal的生命周期就更长,由于一直存在ThreadLocal的强引用,所以ThreadLocal也就不会被回收,也就能保证任何时候都能根据ThreadLocal的弱引用访问到Entry的value值,然后remove它,防止内存泄露。

3.3.2 Android 中的ThreadLocal

​ set()方法:

public void set(T value) {
    Thread currentThread = Thread.currentThread();
    Values values = values(currentThread);
    if (values == null) {
        values = initializeValues(currentThread);
    }
    values.put(this, value);
}

​ 这里新增了一个Values的对象。这个对象定义在ThreadLocal.Values。 每一个Thread中都有一个这样的变量localValues。

Values values(Thread current) {
        return current.localValues;
    }
Values initializeValues(Thread current) {
        return current.localValues = new Values();
    }
void put(ThreadLocal<?> key, Object value) {
    cleanUp();

    // Keep track of first tombstone. That's where we want to go back
    // and add an entry if necessary.
    int firstTombstone = -1;

    for (int index = key.hash & mask;; index = next(index)) {
        Object k = table[index];

        if (k == key.reference) {
            // Replace existing entry.
            table[index + 1] = value;
            return;
        }

        if (k == null) {
            if (firstTombstone == -1) {
                // Fill in null slot.
                table[index] = key.reference;
                table[index + 1] = value;
                size++;
                return;
            }

            // Go back and replace first tombstone.
            table[firstTombstone] = key.reference;
            table[firstTombstone + 1] = value;
            tombstones--;
            size++;
            return;
        }

        // Remember first tombstone.
        if (firstTombstone == -1 && k == TOMBSTONE) {
            firstTombstone = index;
        }
    }
}

​ 这里的算法不去深入探索,但是可以看到,在table数组中存储value的地方。

table[index] = key.reference;
table[index + 1] = value;

​ 接着看下get()方法

 public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }

​ 这里就比较好理解了,返回index+1位置的值。

3.4Handler中的ThreadLocal

​ 具体到Handler中来说,对于每一个Handler它都需要一个唯一对应的Looper。通过ThreadLocal就可以实现在Looper中维护一份ThreadLocal就可以满足不同的线程对应不同的Looper.

 Looper.java
 
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
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));
   }

​ 如果不这样做,那么系统就必须提供一个全局的哈希表供Handler查找指定线程的Looper,这就势必会增加一个类似于LooperManager的类了,这种方法繁琐复杂。系统没有采用这种方案而是采用了ThreadLocal,这就是ThreadLocal的好处。

4. MessageQueue

​ MessageQueue主要包含两个操作enqueneMessage() 和 next()。enqueneMessage作用是向消息队列中插入一条消息,而next则是从消息队列中取出一条消息,同时将其从消息队列中移除。

​ 尽管MessageQueue 叫消息队列,但是它的实现并不是队列,而是一个单链表的数据结构。

5 Looper

    Looper.java
    
    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));
    }

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

​ 在Prepare中会检查当前ThreadLocal是否已经有了looper对象,如果有了就会抛出异常,也就是说prepare()方法一个线程中一个生命周期内只能调用一次。

​ 在构造方法内会new一个MessageQueue,用作消息队列。

​ Looper除了prepare方法外,还提供了prepareMainLooper()方法,这个方法主要是用来给ActivityThread创建Looper使用的,其本质也是调用prepare方法来实现的。但是这个Looper不可以退出。

6.Handler

   private static void handleCallback(Message message) {
        message.callback.run();
    }

这里的CallBack对象是什么:

/**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

这里提示了一种新的构造方法:

Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
      @Override
      public boolean handleMessage(Message msg) {
        return false;
      }
    });

Handler smsHandler = new Handler(){
      public void handleMessage(Message msg) {
        return false;
      };
    };

Message m = Message.obtain(h, new Runnable() {  
        @Override  
        public void run() {  
                //做一些事情,这个run方法是主线程调用的  
        }  
});  
Handler Handler = new Handler();
handler.sendMessage(m);  

​ 如果没有mCallBack,那么最后就会调用handleMessage方法.

run(callback) > mCallBack > handleMessage

7.主线程的消息循环

​ Android的主线程是ActivityThread,主线程的入口方法为main方法。在main方法系统会通过Looper。prepareMainLooper来创建主线程的Looper及MessageQueue,并通过Looper.loop来开启循环。

public static void main(String[] args) {
  
        .....

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

MainLooper也只能prepare一次。

  /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

因为主线程的Looper比较特殊,所有Looper提供了一个getMainLooper的方法来获取。

/**
  * Returns the application's main looper, which lives in the main thread of the application.
 */
public static Looper getMainLooper() {
    synchronized (Looper.class) {
        return sMainLooper;
    }
}

上述会在ActivityThread中开启Looper,并在Looper中初始化MessAgeQueue,这个时候还缺少一个Handler.

Handler是定义在ActivityThread.H中。

private class H extends Handler {
    public static final int LAUNCH_ACTIVITY         = 100;
    public static final int PAUSE_ACTIVITY          = 101;
    public static final int PAUSE_ACTIVITY_FINISHING= 102;
    public static final int STOP_ACTIVITY_SHOW      = 103;
    public static final int STOP_ACTIVITY_HIDE      = 104;
    public static final int SHOW_WINDOW             = 105;
    public static final int HIDE_WINDOW             = 106;
    public static final int RESUME_ACTIVITY         = 107;
    public static final int SEND_RESULT             = 108;
    public static final int DESTROY_ACTIVITY        = 109;
    public static final int BIND_APPLICATION        = 110;
    public static final int EXIT_APPLICATION        = 111;
    public static final int NEW_INTENT              = 112;
    public static final int RECEIVER                = 113;
    public static final int CREATE_SERVICE          = 114;
    public static final int SERVICE_ARGS            = 115;
    public static final int STOP_SERVICE            = 116;
    ...
    
     String codeToString(int code) {
            if (DEBUG_MESSAGES) {
                switch (code) {
                    case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
                    case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
                    case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
                    case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
                    ......
                    }
           }
 }

​ ActivityThread 通过ApplicationThread与AMS进程通信,AMS以进程间通信方试完成ActivityThread的请求后会回调ApplicationThread的Binder方法,然后ApplicationThread会通过H发送消息,H收到消息后会将逻辑切换到ActivityThread中即主线程中进行。这就是主线程的消息循环模型。

8. PS

上一篇 下一篇

猜你喜欢

热点阅读