您的位置:首页 > 其它

Handler解析(一):是如何实现线程之间的切换

2017-07-16 02:27 357 查看
在Android中,一般情况下(特殊情况先不说)只有UI线程才能对View进行操作,然而为了避免ANR等,耗时操作都放到子线程进行,操作完成之后再切换到UI线程,而Handler正好能够完成从子线程切换到UI线程的工作,那么Handler是如何从子线程切换到UI线程的呢?

消息传递机制切换

要了解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时,需要注意内存泄漏的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐