Handler与Thread的关系
来源:互联网 发布:专业配色软件 编辑:程序博客网 时间:2024/04/27 10:12
原文链接如下:http://erqi.github.io/2016/08/31/handler%E5%92%8CThread%E7%9A%84%E5%85%B3%E7%B3%BB/
Looper
Looper是Handler和Thread相关联的桥梁,也是APP开发中线程间通信的用的最多的一个.
然而使用率却是异常的低下,因为在向主线程交互的时Looper该做的工作已经做好,使用上只需要在主线程创建Handler对象,然后再需要的地方发送消息即可.
参考博客 Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系 洪洋
Looper的初始化创建
Looper和线程的关系是一一对应的,每一个线程有且只有一个Looper,可以从Looper的使用中看出.
12345678910
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));}
在使用子线程中使用Hander时,需要有Looper对象,而Looper的构造函数是private修饰的,想要获得创建一个Looper对象就只能调用静态方法prepare.
在方法中我们可以看到调用了sThreadLocal.get()
方法,返回的若非空就会抛出异常.这里就限定了一个线程只能有一个Looper.
Looper的构造函数
1234
private Looper(boolean quitAllowed) {mQueue = new MessageQueue(quitAllowed);mThread = Thread.currentThread();}
在构造函数中创建了一个MessageQueue(消息队列).
Looper的使用
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
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 blockif (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 loggerPrinter 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();}}
当操作完成就可以调用Looper.loop();从代码中可以看出在通过myLooper中拿到了当前线程的Looper对象,获取了对应的MessageQueue之后,该线程会执行一个死循环,在死循环中不停的读取MessageQueue队列中的Message并调用 msg.target.dispatchMessage(msg);去处理该消息.
Handler
在使用Handler时,我们通常都是实例化一个对象去发送消息,然后在handleMessage方法中去处理对应的消息,并作出对应的处理.
Hanlder的初始化
1234567891011121314151617181920212223
public Handler() {this(null, false);}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) {Log.w(TAG, "The following Handler class should be static or leaks might occur: " +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进行了关联,如若在子线程中未创建Looper就创建Hanlder那么便会抛出异常.并且在下面继续获取了Looper的消息队列.
Handler的使用
1234
Message message = Message.obtain();message.what = TEXT;message.obj = (int) (Math.random() * 1000);mHandler.sendMessage(message);
Handler使用方式十分之简单,在需要使用的地方发送一个Message消息即可,在创建Handler时重写handleMessage方法中处理对应的Message消息即可.
多数人走到这一步就停下了,因为已经知道如何使用Hanlder和Looper了,能满足跨线程交互需求了,也就没有继续探索的愿望了,然后在面试的一个一问Handler为什么能切换到主线程去执行对应的方法就懵逼了(面试问懵逼好几个了….)
Handler跨线程的原因
既然发送消息是在子线程,在handleMessage中处理的时候已经到了主线程,那么线程切换的奥秘一定就在这两个方法调用过程中,我们就从sendMessage方法中一步一步往下看.
1234567891011121314151617181920212223
public final boolean sendMessage(Message msg){return sendMessageDelayed(msg, 0);}public final boolean sendMessageDelayed(Message msg, long delayMillis){if (delayMillis < 0) {delayMillis = 0;}return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);}public boolean sendMessageAtTime(Message msg, long uptimeMillis) {MessageQueue queue = mQueue;if (queue == null) {RuntimeException e = new RuntimeException(this + " sendMessageAtTime() called with no mQueue");Log.w("Looper", e.getMessage(), e);return false;}return enqueueMessage(queue, msg, uptimeMillis);}
到这里就可以看出一点端倪了,mQueue出现了,也就是Handler在创建时获取的Looper的MessageQueue对象.
我们继续向下看
1234567
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
在Looper.loop中我们看到msg.target.dispatchMessage(msg);
这么一行代码,现在稍微一推敲就知道最终发生了什么,怎么切换线程的,但是我们还是继续往下看.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
boolean enqueueMessage(Message msg, long when) {if (msg.target == null) {throw new IllegalArgumentException("Message must have a target.");}if (msg.isInUse()) {throw new IllegalStateException(msg + " This message is already in use.");}synchronized (this) {if (mQuitting) {IllegalStateException e = new IllegalStateException(msg.target + " sending message to a Handler on a dead thread");Log.w(TAG, e.getMessage(), e);msg.recycle();return false;}msg.markInUse();msg.when = when;Message p = mMessages;boolean needWake;if (p == null || when == 0 || when < p.when) {// New head, wake up the event queue if blocked.msg.next = p;mMessages = msg;needWake = mBlocked;} else {// Inserted within the middle of the queue. Usually we don't have to wake// up the event queue unless there is a barrier at the head of the queue// and the message is the earliest asynchronous message in the queue.needWake = mBlocked && p.target == null && msg.isAsynchronous();Message prev;for (;;) {prev = p;p = p.next;if (p == null || when < p.when) {break;}if (needWake && p.isAsynchronous()) {needWake = false;}}msg.next = p; // invariant: p == prev.nextprev.next = msg;}// We can assume mPtr != 0 because mQuitting is false.if (needWake) {nativeWake(mPtr);}}return true;}
恩,到这里就是将Message加入到消息队列中去中去,hanlder中消息发送流程已经走完了.
在这里handler将Message加入到了消息队列中,而Looper一直线主线程中阻塞着,所以一收到消息就拿到了Message对象,然后在主线程中调用了Hanlder的处理方法.
Looper对消息的处理
从上面的分析已经了解到了子线程和主线程是如何切换的,我们继续看在主线程中Looper是如何处理发送过来的消息的.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
// Looper.loop();中代码Message msg = queue.next(); // might block// MessageQueue中next();代码Message next() {// Return here if the message loop has already quit and been disposed.// This can happen if the application tries to restart a looper after quit// which is not supported.final long ptr = mPtr;if (ptr == 0) {return null;}int pendingIdleHandlerCount = -1; // -1 only during first iterationint nextPollTimeoutMillis = 0;for (;;) {if (nextPollTimeoutMillis != 0) {Binder.flushPendingCommands();}nativePollOnce(ptr, nextPollTimeoutMillis);synchronized (this) {// Try to retrieve the next message. Return if found.final long now = SystemClock.uptimeMillis();Message prevMsg = null;Message msg = mMessages;if (msg != null && msg.target == null) {// Stalled by a barrier. Find the next asynchronous message in the queue.do {prevMsg = msg;msg = msg.next;} while (msg != null && !msg.isAsynchronous());}if (msg != null) {if (now < msg.when) {// Next message is not ready. Set a timeout to wake up when it is ready.nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);} else {// Got a message.mBlocked = false;if (prevMsg != null) {prevMsg.next = msg.next;} else {mMessages = msg.next;}msg.next = null;if (DEBUG) Log.v(TAG, "Returning message: " + msg);msg.markInUse();return msg;}} else {// No more messages.nextPollTimeoutMillis = -1;}// Process the quit message now that all pending messages have been handled.if (mQuitting) {dispose();return null;}// If first time idle, then get the number of idlers to run.// Idle handles only run if the queue is empty or if the first message// in the queue (possibly a barrier) is due to be handled in the future.if (pendingIdleHandlerCount < 0&& (mMessages == null || now < mMessages.when)) {pendingIdleHandlerCount = mIdleHandlers.size();}if (pendingIdleHandlerCount <= 0) {// No idle handlers to run. Loop and wait some more.mBlocked = true;continue;}if (mPendingIdleHandlers == null) {mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];}mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);}// Run the idle handlers.// We only ever reach this code block during the first iteration.for (int i = 0; i < pendingIdleHandlerCount; i++) {final IdleHandler idler = mPendingIdleHandlers[i];mPendingIdleHandlers[i] = null; // release the reference to the handlerboolean keep = false;try {keep = idler.queueIdle();} catch (Throwable t) {Log.wtf(TAG, "IdleHandler threw exception", t);}if (!keep) {synchronized (this) {mIdleHandlers.remove(idler);}}}// Reset the idle handler count to 0 so we do not run them again.pendingIdleHandlerCount = 0;// While calling an idle handler, a new message could have been delivered// so go back and look again for a pending message without waiting.nextPollTimeoutMillis = 0;}}
瞧,我们发现了什么,又是一个死循环阻塞,原来主线程不是阻塞在Looper中,而是阻塞在MessageQueue对象中.
可以看到当消息队列有消息的时候立马返回消息,没有消息就阻塞(我就偷了个懒,不在继续深入MessageQueue的原理了…)
Looper收到返回的消息会调用msg.target.dispatchMessage(msg)去处理,也就是调用Handler去处理.
我们继续来到Hanlder的处理方法中.
123456789101112
public void dispatchMessage(Message msg) {if (msg.callback != null) {handleCallback(msg);} else {if (mCallback != null) {if (mCallback.handleMessage(msg)) {return;}}handleMessage(msg);}}
msg.callback我们先放一放,就我们普通发送的Message通常是没有callback对象的,下面的mCallback我们来看一看,该对象出现在构造函数之中,通过构造函数来赋值,我们来看看这个对象的定义
123
public interface Callback {public boolean handleMessage(Message msg);}
可以看出就是一个接口,和自己重写handleMessage一样,只不过提供另一种方式来处理.(说实话,在成员对象创建上面还重写其方法,我感觉是看着挺难受的,这样抽取成对象,然后通过构造函数传递进去,看着舒服多了.)
回到正题中来,我们还剩下一个Messaged的callBack对象没整明白.
首先,我们来看一看这究竟是一个什么对象.
1
/*package*/ Runnable callback;
可以看到就是一个任务而已,而handleCallback(msg)方法点进去再来看一看
123
private static void handleCallback(Message message) {message.callback.run();}
只是单纯的是运行这个任务而已,但是这个任务是哪里来的呢?
答案在Handler,Handler不仅可以发消息给自己在主线程处理,也可以直接发送一个任务去主线程运行.
12345678910
public final boolean post(Runnable r){return sendMessageDelayed(getPostMessage(r), 0);}private static Message getPostMessage(Runnable r) {Message m = Message.obtain();m.callback = r;return m;}
到这里也就看明白了,剩下就和普通消息一样的处理方式了.
- Handler与Thread的关系
- Android Thread 与 Handler 的关系
- android中Thread、handler(Handler Thread)、Runnable之间的关系
- Handler,Looper,Thread之间的关系
- Looper、Handler和Thread的关系
- 详解Handler和Looper、Thread的关系
- 野人学Android第二弹——Handler与Thread之间的关系
- Handler与Looper的关系
- Handler与线程的关系
- Service 与 Thread 的关系
- 实例与thread#的关系
- process与thread的关系
- Thread与Runnable的关系
- Android Thread Looper Handler 关系
- Android Thread Looper Handler 关系
- Android Thread Looper Handler 关系
- Handler Looper Messagequeue Thread关系
- Handler Runnable与Thread的区别详解
- 应用层打开驱动层创建的符号链接
- vsb教程《运行程序》
- 安装cuda8.0时无法安装.net Framework 4.0 错误的解决
- ssh远程控制
- VR平台开发笔记(四).net添加与删除文件夹
- Handler与Thread的关系
- 序列化与网络传输
- C++学习笔记(2)之引用详解
- poi处理excel时需要注意的一些点
- PHP打开文件于读取修改小方法
- LeetCode----best-time-to-buy-and-sell-stock
- Servlet技术(一)
- Replace into与Insert update
- jvm垃圾回收