booleanenqueueMessage(Message msg, long when){ // msg 必须有target也就是必须有handler if (msg.target == null) { thrownew IllegalArgumentException("Message must have a target."); } if (msg.isInUse()) { thrownew 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(); returnfalse; }
msg.markInUse(); //when 表示这个消息执行的时间,队列是按照消息执行时间排序的 //如果handler 调用的是postDelay 那么when=SystemClock.uptimeMillis()+delayMillis msg.when = when; Message p = mMessages; boolean needWake; if (p == null || when == 0 || when < p.when) { // p==null 表示当前消息队列没有消息 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; //将消息放到队列的确切位置,队列是按照msg的when 排序的,链表操作自己看咯 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.next prev.next = msg; }
// 如果需要唤醒Looper线程,这里调用native的方法实现epoll机制唤醒线程,我们就不在深入探讨了 if (needWake) { nativeWake(mPtr); } } returntrue; }
//Looper 所属的线程的消息队列 final MessageQueue mQueue; //Looper 所属的线程 final Thread mThread;
publicstaticvoidprepare(){ prepare(true); }
privatestaticvoidprepare(boolean quitAllowed){ //如果线程的TLS已有数据,则会抛出异常,一个线程只能有一个Looper,prepare不能重复调用。 if (sThreadLocal.get() != null) { thrownew RuntimeException("Only one Looper may be created per thread"); } //往线程的TLS插入数据,简单理解相当于map.put(Thread.currentThread(),new Looper(quitAllowed)); sThreadLocal.set(new Looper(quitAllowed)); }
这里首先执行的是Looper.prepareMainLooper()方法,执行完Looper.prepareMainLooper() 之后下一句代码是ActivityThread thread = new ActivityThread();这句话就是创建一下ActivityThread对象,这边需要注意的时候ActivityThread并不是一个线程,它并没有继承Thread,而只是一个普通的类public final class ActivityThread{…}ActivityThread的构造函数并没有做什么事只是初始化了资源管理器。
publicstaticvoidloop(){ final Looper me = myLooper(); //获取TLS存储的Looper对象,获取当前线程的Looper if (me == null) { thrownew RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; //获取Looper对象中的消息队列 ....