理解Handler,Looper,MessageQueue,ThreadLocal关系

理解Handler,Looper,MessageQueue,ThreadLocal关系

  • ThreadLocal简单介绍
  • 源码分析Looper,messagequeue,handler
  • 关系总结

1、ThreadLocal介绍
ThreadLocal是一个线程内部的数据存储类,对于存储和获取数据都只能在对应的线程中,线程间的数据相互不影响,所以在处理并发时,可以使用线程安全机制(锁),也可以使用ThreadLocal,两个区别:个人理解为线程锁是使用时间获取空间,有且只有一个线程对数据进行操作,而ThreadLocal的话是空间获取时间,线程间相互不影响,而且,一般使用threadlocal的地方比较少,如Looper,activitythread,activitymanagerservice等。threadlocal提供set,get,remove的方法对存储数据进行操作,对于高版本的jdk,threadlocal是可以存储T泛型,而地版本还是只针对object。

2、Looper,messagequeue,handler
looper可以理解为消息循环,messagequeue可以理解为消息队列,handler可以理解为消息操作,
1)Looper:
从成员变量来看,有messagequeue,threadlocal,looper等,上面说过threadlocal是数据存储类,我们知道handler是系统上层提供给我们间接操作UI线程更新布局,我们会在不同的子线程中sendMessage来更新布局,所以此处使用了threadlocal来处理线程安全,在构造函数中会new messagequeue,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));
}

public static void loop() {
    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;

    // Make sure the identity of this thread is that of the local process,
    // and keep track of what that identity token actually is.
    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    for (;;) {
        Message msg = queue.next(); // might block
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }

        // This must be in a local variable, in case a UI event sets the logger
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(msg);

        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }

        msg.recycleUnchecked();
    }
}

prepare方法中,throw exception表示一个线程中只能有一个Looper,如果为空的话,通过set方法设置一个looper进去,同样还有就是preparemainLooper的方法是针对主线程的,在我们的应用启动后,系统会自动获取sMainLooper。
loop方法:通过myLooper方法从threadlocal中获取到对应线程中的looper,所以这两个方法的执行顺序是先prepare,然后才是loop。再者进入for(;;)的无限循环,通过Message msg = queue.next(),获取一条message,然后通过msg.target.dispatchMessage(msg)进行message处理,msg.target其实就是handler,最后别忘了msg的recycle。然后我们看看消息处理:

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

这里有个判断,我们这里注意下else中,handleMessage,handleMessage是一个空方法,其实这个是handler中我们自己实现的一个方法,有印象吗?而if中是针对我们handler.post(runnable).
2)Handler:
在构造函数中会得到对应的looper,messagequeue,然后查看sendmessage方法,发现最后调用的是enqueueMessage,

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

这里可以看到msg.target = this;及handler,最后调用queue.enqueueMessage(msg, uptimeMillis),表示handler发出去的message会保存在messagequeue中,这样就达到循环啦。

3、总结
1、首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。
2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。
3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue想关联。
4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。
5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。
好了,总结完成,大家可能还会问,那么在Activity中,我们并没有显示的调用Looper.prepare()和Looper.loop()方法,为啥Handler可以成功创建呢,这是因为在Activity的启动代码中,已经在当前UI线程调用了Looper.prepare()和Looper.loop()方法。

Looper.loop无限循环的让消息出队列,或者处于闭塞状态,MessageQueue的enqueueMessage()就是入队列的方法,根据时间(long)。有三种方法可以更新UI:
1. Handler的post()方法

  1. View的post()方法

  2. Activity的runOnUiThread()方法
    最后都还是调用Handler来处理。

注:本人水平有限,仅供参考,如有不正确的地方还请指出,仅为日后需要使用
参考文档:
http://blog.csdn.net/lmj623565791/article/details/38377229

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值