Handler解析(一):是如何实现线程之间的切换
2017-07-16 02:27
387 查看
在Android中,一般情况下(特殊情况先不说)只有UI线程才能对View进行操作,然而为了避免ANR等,耗时操作都放到子线程进行,操作完成之后再切换到UI线程,而Handler正好能够完成从子线程切换到UI线程的工作,那么Handler是如何从子线程切换到UI线程的呢?
1.Message
消息,即线程间传递的对象,传递的信息包含在其中。例如后台线程在处理数据完毕后需要更新UI,则可发送一条包含更新信息的Message给UI线程。
2. Message Queue
消息队列,用来存放通过Handler发布的消息,按照先进先出执行。
3. Handler
Handler是Message的主要处理者,负责将Message添加到消息队列以及对消息队列中的Message进行处理。
4. Looper
循环器,扮演Message Queue和Handler之间桥梁的角色,循环取出Message Queue里面的Message,并交付给相应的Handler进行处理。
它们之间的协作如下图,
Handler的构造函数,在构造函数中初始化了一个Looper
4000
和 MessageQueue。
可以发现Looper.myLooper()是通过ThreadLocal中读取出来的,而在Handler的构造函数中,若Looper.myLooper()返回为null,则会抛出RuntimeException;而myLooper()函数被@Nullable修饰,说明它是可以返回为null的,我们必须要保证在初始化Handler的时候,myLooper()不会返回为null。那继续看看sThreadLocal是在哪里初始化的
在Looper中,有一个prepare的函数,在其中对Looper进行了初始化,Looper对象保存在sThreadLocal中。那接下来看看ThreadLocal是何物
其中通过 Thread.currentThread()获取了当前所在线程,然后通过getMap读取当前线程的属性threadLocals,返回一个ThreadLocalMap对象,然后从map中读取或者写入当前的值。
通过代码可以发现ThreadLocalMap其实内部维护了一个Entry的数组。其中值得注意的是Entry的key为弱引用,value为强引用。所以通过ThreadLocal来保存的话,线程未推出之前,value会一直被引用,从而可能导致内存泄漏。
通过上面的代码分析,可以了解到,通过Looper.prepare()创建的looper是保存在当前线程的threadLocals中,不同线程调用Looper.prepare()创建looper会将looper对象保存在对应的线程当中,保证了不同线程之前的looper实例单独保存,互不影响。
Looper的构造函数初始化了一个MessageQueue,从上面的结论可以得知,不同线程调用Looper.prepare()创建looper会将looper对象保存在对应的线程当中,保证了不同线程之前的looper实例单独保存,互不影响。同理,不同线程之间的MessageQueue也是单独保存,互不影响。
因此我们可以得知,Handler在当前线程初始化,则它对应的Looper和MessageQueue都保存在当前的线程当中,与其它的线程是隔离开来的。再来看看Looper中的loop函数,它负责从MessageQueue中取出message。
从loop函数中我们可以发现最终调用了 msg.target.dispatchMessage(msg);其中的target即发送消息的handler。
通过上面的分析我们可以知道,当在A线程中创建handler的时候,同时创建了MessageQueue与Looper,Looper在A线程中调用loop进入一个无限的for循环从MessageQueue中取消息,当B线程调用handler发送一个message的时候,会通过msg.target.dispatchMessage(msg);将message插入到handler对应的MessageQueue中,Looper发现有message插入到MessageQueue中,便取出message执行相应的逻辑,因为Looper.loop()是在A线程中启动的,所以则回到了A线程,达到了从B线程切换到A线程的目的。
2.通过Handler发送消息时,消息会回到Handler初始化的线程,而不一定是主线程。
3.使用ThreadLocal时,需要注意内存泄漏的问题。
消息传递机制切换
要了解Handler,就首先需要了解Android的消息传递机制,整个消息传递机制有四部分组成:1.Message
消息,即线程间传递的对象,传递的信息包含在其中。例如后台线程在处理数据完毕后需要更新UI,则可发送一条包含更新信息的Message给UI线程。
2. Message Queue
消息队列,用来存放通过Handler发布的消息,按照先进先出执行。
3. Handler
Handler是Message的主要处理者,负责将Message添加到消息队列以及对消息队列中的Message进行处理。
4. Looper
循环器,扮演Message Queue和Handler之间桥梁的角色,循环取出Message Queue里面的Message,并交付给相应的Handler进行处理。
它们之间的协作如下图,
Handler
首先来看看Handler的实现源码public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { klass.getCanonicalName()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; }
Handler的构造函数,在构造函数中初始化了一个Looper
4000
和 MessageQueue。
Looper
接下来看看Looper.myLooper()的实现static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
可以发现Looper.myLooper()是通过ThreadLocal中读取出来的,而在Handler的构造函数中,若Looper.myLooper()返回为null,则会抛出RuntimeException;而myLooper()函数被@Nullable修饰,说明它是可以返回为null的,我们必须要保证在初始化Handler的时候,myLooper()不会返回为null。那继续看看sThreadLocal是在哪里初始化的
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)); }
在Looper中,有一个prepare的函数,在其中对Looper进行了初始化,Looper对象保存在sThreadLocal中。那接下来看看ThreadLocal是何物
ThreadLocal
看ThreadLocal中get()与set()的源码如下public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue(); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
其中通过 Thread.currentThread()获取了当前所在线程,然后通过getMap读取当前线程的属性threadLocals,返回一个ThreadLocalMap对象,然后从map中读取或者写入当前的值。
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; } } /...省略代码若干.../ 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); }
通过代码可以发现ThreadLocalMap其实内部维护了一个Entry的数组。其中值得注意的是Entry的key为弱引用,value为强引用。所以通过ThreadLocal来保存的话,线程未推出之前,value会一直被引用,从而可能导致内存泄漏。
通过上面的代码分析,可以了解到,通过Looper.prepare()创建的looper是保存在当前线程的threadLocals中,不同线程调用Looper.prepare()创建looper会将looper对象保存在对应的线程当中,保证了不同线程之前的looper实例单独保存,互不影响。
MessageQueue
接下里看看MessageQueue,从Handler的源码中可以发现,Handler所对应的MessageQueue是从Looper中获取的,private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
Looper的构造函数初始化了一个MessageQueue,从上面的结论可以得知,不同线程调用Looper.prepare()创建looper会将looper对象保存在对应的线程当中,保证了不同线程之前的looper实例单独保存,互不影响。同理,不同线程之间的MessageQueue也是单独保存,互不影响。
因此我们可以得知,Handler在当前线程初始化,则它对应的Looper和MessageQueue都保存在当前的线程当中,与其它的线程是隔离开来的。再来看看Looper中的loop函数,它负责从MessageQueue中取出message。
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; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { return; } final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } try { msg.target.dispatchMessage(msg); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } 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(); } }
从loop函数中我们可以发现最终调用了 msg.target.dispatchMessage(msg);其中的target即发送消息的handler。
如何实现线程之间切换
最终回到Handler是如何实现线程之间的切换的呢?例如现在有A、B两个线程,在A线程中有创建了handler,然后在B线程中调用handler发送一个message。通过上面的分析我们可以知道,当在A线程中创建handler的时候,同时创建了MessageQueue与Looper,Looper在A线程中调用loop进入一个无限的for循环从MessageQueue中取消息,当B线程调用handler发送一个message的时候,会通过msg.target.dispatchMessage(msg);将message插入到handler对应的MessageQueue中,Looper发现有message插入到MessageQueue中,便取出message执行相应的逻辑,因为Looper.loop()是在A线程中启动的,所以则回到了A线程,达到了从B线程切换到A线程的目的。
总结
1.Handler初始化之前,Looper必须初始化完成。UI线程之所以不用初始化,因为在ActivityThread已经初始化,其他子线程初始化Handler时,必须先调用Looper.prepare()。2.通过Handler发送消息时,消息会回到Handler初始化的线程,而不一定是主线程。
3.使用ThreadLocal时,需要注意内存泄漏的问题。
相关文章推荐
- Handler是如何实现线程之间的切换的
- 源码分析Android Handler是如何实现线程间通信的
- Android使用Handler实现子线程与子线程、主线程之间通信
- Android Handler如何实现线程间通信,源码分析。
- 如何自己写一个容器来实现viewController之间的切换
- Flex 如何实现按钮之间的切换,按钮点击事件
- iOS应用之间跳转 本篇博文将涉及到以下知识点: app应用跳转的原理解析 如何实现两个app应用之间的跳转 如何实现两个app之间跳转到指定界面 二、应用跳转原理 相信从一个应用跳转到另一个应用
- java多线程有几种实现方法?线程之间如何同步
- Android 使用handler实现线程间发送消息 (主线程 与 子线程之间)、(子线程 与 子线程之间)
- vue中如何实现样式之间的切换
- Gridview如何实现敲回车进入下一行,或者用方向键在不同的行之间切换?
- Handler实现线程之间的通信下载文件动态更新进度条
- 浅析Java中如何实现线程之间通信
- java学习——如何实现线程之间的通信 ,Condition 的使用
- 如何实现3G/4G与Wi-Fi网络之间稳定且无缝地切换
- python高效编程技巧13(如何在线程之间实现事件通知)
- 使用Handler实现主线程与子线程之间互相传递消息
- java多线程有几种实现方法?线程之间如何同步
- android脚步---如何看log之程序停止运行,和UI线程和非UI线程之间切换