handler ,Looper的机制,分析源码(一)线程切换。
2016-08-18 18:26
351 查看
handler和looper配合使用是为了线程之间通信用的。
这里拿一个我们经常使用handler的简单例子说明(伪代码):
这样run()里面的代码就是在主线程跑的了。
从这个例子入手,去分析。
1、先看post的源码
里面调了sendMessageDelayed,这个很多人也用过,第一个参数应该是个Message对象,看看getPostMessage里面做了什么:
里面创建了一个Message对象,并且把我们new 的Runnable对象赋值给了Message对象的callback。
这么说来这里的callback就是一个Runnable对象。有什么用呢?
2、接着看sendMessageDelayed。
3、没啥说的,继续跟:
这里看到有个MessageQueue的实例mQueue,看看它哪来的:
是在Handler的构造函数里的,new Handler()里是调了这个构造函数的。由looper给的,一个Looper中有MessageQueque成员。先不急着回去,既然来了就瞧一眼handler初始化都做什么。首先,实例化了一个looper。
mLooper = Looper.myLooper();
好奇myLooper()做了什么。点进去!
api里面说了,返回一个绑定当前线程的Looper。如果这个线程没有和一个looper对象绑定,会返回空。什么时候绑定的呢?留个悬念。
回到3、继续跟enqueueMessage方法
给msg的target赋值了。然后将msg入队列。
target是个啥?这里赋值了this,也就是是一个Handler对象。
这就有个问题了,我们不是调了handler.post()才跟进来的吗,怎么又给target赋值了一个handler?这个handler和handler.post()的handler是一个吗?又看到,调用了queue.enqueueMessage。之前说了,一个Looper绑定一个线程,一个Looper对象中有MessageQueue成员。
理一下过程:在实例化handler的时候,拿到了当前线程 的looper,通过looper访问MessageQueue,将msg入队列。这个过程中msg 的变化:msg.callback(一个runnable对象)赋值了,msg.target赋值了(一个handler)对象。
那之后呢?往队列里加msg完成了,什么时候去拿呢。
是在Looper.loop()方法里。
看看做了什么吧?
先是从当前线程中获取一个looper实例再从looper中获取MessageQueue,也就是这个线程处理的queue。然后遍历这个队列,重点来了
msg.target.dispatchMessage(msg);
上面说了target就是一个handler实例。既然每个message对象都是通过handler,且把它作为target进入队列,那么这个时候msg.target就是把它丢进队列的那个handler。也就是说,对于msg的处理最后还是交给了将它放进队列的Handler,那么自然的,这个handler在哪个线程,msg就在哪个线程处理了。
再跟着看dispatchMessage里面:
如果msg的callback也就是我们post传入的runnable不为空,那么优先处理它,然后如果handler自己的callback不为空,交给他处理。这个自身的callback是有个handler的构造函数初始化的(我们的例子里,这个是空)。最后就走到了handleMessage:
是的,你没看错,这个就是我们常用的handler用法另一个例子:继承Handler类并且重写handleMessage方法。
。
这时候估计有人会问这个loop方法你怎么知道一定是用它从队列里取msg并且处理的呢?我们的例子里面没有用啊。那是因为在ActivityThread也就是应用的主线程中,已经默认把这步做了:
你看是的吧。
我们自己在子线程用的话,就要自己去做Looper.prepare()和Looper.loop()方法,Looper类的api已经告诉了我们怎么用:
再来总结一下:
一个线程对应一个looper对应一个messagequeue,一个handler对应一个message,前后是一对多的关系。
也许有人问,哪里看出一个线程对应一个looper呢?好像每次入队列或者出队列都是从当前线程获取一个looper对象啊,这两个是一个吗?
我们看prepare()方法:
看它给抛出的异常:Only one Looper may be created per thread。
这个地方也指出了之前留的疑问,什么时候一个线程绑定的Looper呢,就是在Looper.prepare()方法里。只是这个过程通常我们用的时候实在主线程,ActivityThread帮我们做了。正常的流程是:
Looper.prepare() 创建一个和当前线程绑定的looper(把looper放在threadLocal中) 和MessageQueue;
实例化一个handler,handler实例化的时候拿到handler所在线程的looper;
通过这个looper拿到MessageQueque;
生成一个Message对象并把runnable和当前handler给它;
把这个Message对象写入MessageQueque;
Looper.loop()拿到当前线程的looper(和上面的looper是同一个);
从这个looper中拿MessageQueque;
遍历MessageQueque拿到Message对象;
交由Message中的handler也就是2中的handler处理;
handler.dispatchMessage()去做消息的分发,
这个过程可以大体上理解为两部分,一个是往MessageQueue里放的,另一部分是从MessageQueue里面取的。具体的,Handler类可以提供“放”操作,Looper类提供取操作,Handler在初始化的时候就绑定了处理MessageQueue的Looper 。
然后看一段代码:
这段代码中,虽然②的动作发生在子线程,但是①在初始化的时候就决定了处理MessageQueue的是主线程的Looper。所以做后的执行还是在主线程执行。尽管在一个新起的线程中作了handler.post的操作,但是post()中的run()在哪个线程仅由handler(处理MessageQueue的Looper)所在的线程决定。
这里拿一个我们经常使用handler的简单例子说明(伪代码):
mianTread:{ Handler handler =new Handler(); } childThread:{ handler.post(new Runnable(){ run(){ do something。。。 } }) }
这样run()里面的代码就是在主线程跑的了。
从这个例子入手,去分析。
1、先看post的源码
public final boolean post(Runnable r) { return sendMessageDelayed(getPostMessage(r), 0); }
里面调了sendMessageDelayed,这个很多人也用过,第一个参数应该是个Message对象,看看getPostMessage里面做了什么:
private static Message getPostMessage(Runnable r) { Message m = Message.obtain(); m.callback = r; return m; }
里面创建了一个Message对象,并且把我们new 的Runnable对象赋值给了Message对象的callback。
这么说来这里的callback就是一个Runnable对象。有什么用呢?
2、接着看sendMessageDelayed。
public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); }
3、没啥说的,继续跟:
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); }
这里看到有个MessageQueue的实例mQueue,看看它哪来的:
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的构造函数里的,new Handler()里是调了这个构造函数的。由looper给的,一个Looper中有MessageQueque成员。先不急着回去,既然来了就瞧一眼handler初始化都做什么。首先,实例化了一个looper。
mLooper = Looper.myLooper();
好奇myLooper()做了什么。点进去!
/** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
api里面说了,返回一个绑定当前线程的Looper。如果这个线程没有和一个looper对象绑定,会返回空。什么时候绑定的呢?留个悬念。
回到3、继续跟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赋值了。然后将msg入队列。
target是个啥?这里赋值了this,也就是是一个Handler对象。
这就有个问题了,我们不是调了handler.post()才跟进来的吗,怎么又给target赋值了一个handler?这个handler和handler.post()的handler是一个吗?又看到,调用了queue.enqueueMessage。之前说了,一个Looper绑定一个线程,一个Looper对象中有MessageQueue成员。
理一下过程:在实例化handler的时候,拿到了当前线程 的looper,通过looper访问MessageQueue,将msg入队列。这个过程中msg 的变化:msg.callback(一个runnable对象)赋值了,msg.target赋值了(一个handler)对象。
那之后呢?往队列里加msg完成了,什么时候去拿呢。
是在Looper.loop()方法里。
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */ 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.clearCalling c970 Identity(); 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(); } }
看看做了什么吧?
先是从当前线程中获取一个looper实例再从looper中获取MessageQueue,也就是这个线程处理的queue。然后遍历这个队列,重点来了
msg.target.dispatchMessage(msg);
上面说了target就是一个handler实例。既然每个message对象都是通过handler,且把它作为target进入队列,那么这个时候msg.target就是把它丢进队列的那个handler。也就是说,对于msg的处理最后还是交给了将它放进队列的Handler,那么自然的,这个handler在哪个线程,msg就在哪个线程处理了。
再跟着看dispatchMessage里面:
/** * Handle system messages here. */ public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
如果msg的callback也就是我们post传入的runnable不为空,那么优先处理它,然后如果handler自己的callback不为空,交给他处理。这个自身的callback是有个handler的构造函数初始化的(我们的例子里,这个是空)。最后就走到了handleMessage:
/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
是的,你没看错,这个就是我们常用的handler用法另一个例子:继承Handler类并且重写handleMessage方法。
。
这时候估计有人会问这个loop方法你怎么知道一定是用它从队列里取msg并且处理的呢?我们的例子里面没有用啊。那是因为在ActivityThread也就是应用的主线程中,已经默认把这步做了:
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();
你看是的吧。
我们自己在子线程用的话,就要自己去做Looper.prepare()和Looper.loop()方法,Looper类的api已经告诉了我们怎么用:
/** * Class used to run a message loop for a thread. Threads by default do * not have a message loop associated with them; to create one, call * {@link #prepare} in the thread that is to run the loop, and then * {@link #loop} to have it process messages until the loop is stopped. * * <p>Most interaction with a message loop is through the * {@link Handler} class. * * <p>This is a typical example of the implementation of a Looper thread, * using the separation of {@link #prepare} and {@link #loop} to create an * initial Handler to communicate with the Looper. * * <pre> * class LooperThread extends Thread { * public Handler mHandler; * * public void run() { * Looper.prepare(); * * mHandler = new Handler() { * public void handleMessage(Message msg) { * // process incoming messages here * } * }; * * Looper.loop(); * } * }</pre>
再来总结一下:
一个线程对应一个looper对应一个messagequeue,一个handler对应一个message,前后是一对多的关系。
也许有人问,哪里看出一个线程对应一个looper呢?好像每次入队列或者出队列都是从当前线程获取一个looper对象啊,这两个是一个吗?
我们看prepare()方法:
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)); }
看它给抛出的异常:Only one Looper may be created per thread。
这个地方也指出了之前留的疑问,什么时候一个线程绑定的Looper呢,就是在Looper.prepare()方法里。只是这个过程通常我们用的时候实在主线程,ActivityThread帮我们做了。正常的流程是:
Looper.prepare() 创建一个和当前线程绑定的looper(把looper放在threadLocal中) 和MessageQueue;
实例化一个handler,handler实例化的时候拿到handler所在线程的looper;
通过这个looper拿到MessageQueque;
生成一个Message对象并把runnable和当前handler给它;
把这个Message对象写入MessageQueque;
Looper.loop()拿到当前线程的looper(和上面的looper是同一个);
从这个looper中拿MessageQueque;
遍历MessageQueque拿到Message对象;
交由Message中的handler也就是2中的handler处理;
handler.dispatchMessage()去做消息的分发,
这个过程可以大体上理解为两部分,一个是往MessageQueue里放的,另一部分是从MessageQueue里面取的。具体的,Handler类可以提供“放”操作,Looper类提供取操作,Handler在初始化的时候就绑定了处理MessageQueue的Looper 。
然后看一段代码:
①Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Log.i("thread","out"+Thread.currentThread().getId()+""); ②handler.post(new Runnable() { @Override public void run() { Log.i("thread",Thread.currentThread().getId()+""); } }); } }).start();
这段代码中,虽然②的动作发生在子线程,但是①在初始化的时候就决定了处理MessageQueue的是主线程的Looper。所以做后的执行还是在主线程执行。尽管在一个新起的线程中作了handler.post的操作,但是post()中的run()在哪个线程仅由handler(处理MessageQueue的Looper)所在的线程决定。
相关文章推荐
- Linux资源监控命令/工具(综合)
- Openfire使用上的一些技巧
- linux下查看系统进程占用的句柄数
- 雅虎网站页面性能优化的34条黄金守则
- Linux设备模型之kset
- Linux下javaweb环境搭建
- 内存溢出的多种原因及优化方法
- centos搭建基于mysql验证的SVN
- 查看linux的端口使用情况
- Centos 7 开启端口
- linux 顶层Makefile执行的流程!!!
- linux下反编译apk
- OpenCV实现图像亮区扩张
- linux下web测试环境的搭建94
- centos 7 下安装cobbler报“ Apps aren't loaded yet”
- 在py-faster-rcnn/lib里make时报错: unrecognized command line option ‘-Wdate-time’
- Nginx站点缓存设置
- jni应用(*isCopy 返回的说明)
- Linux系统下文件赋权指令chmod和文件所有权指令chown详解
- centos下的selenium+phantomjs