首先看看在Android中,是怎么使用Handler往子线程发送消息的
publicstaticMessageobtain(){synchronized(sPoolSync){if(sPool!=null){Messagem=sPool;sPool=m.next;m.next=null;m.flags=0;//clearin-useflagsPoolSize--;returnm;}}returnnewMessage();}这里对Message的复用做了同步处理,如果Message池不为空,将sPool指针后移一个,将原来的头结点m返回,同时计数减1。这是非常熟悉的单链表操作。如果没有可以复用的,那么就创建一个新的Message。其他的obtain方法的重载都会调用此方法,然后将传入参数重新赋值。
在没有设置同步屏障时,普通消息和异步消息没有不同,设置同步屏障之后,同步屏障之前的消息正常执行,同步屏障之后的所有同步消息不能执行,异步消息会优先执行;
同步屏障需要手动移除,同步屏障如果一直不移除,当所有异步消息执行完之后,线程会被挂起。
同步屏障一般是系统行为,我们无法手动调用,除非反射;Android中View的绘制任务就是通过发送同步屏障和异步消息的方式实现的。
nativePollOnce(ptr,nextPollTimeoutMillis);synchronized(this){//Trytoretrievethenextmessage.Returniffound.finallongnow=SystemClock.uptimeMillis();//指向前一个messageMessageprevMsg=null;//初始时指向第一个messageMessagemsg=mMessages;//1msg.target==null说明遇到消息屏障if(msg!=null&&msg.target==null){//能进入这个if,说明此时的msg是屏障消息//循环遍历,退出循环的条件是,message到末尾了,或者//msg是异步消息do{prevMsg=msg;msg=msg.next;}while(msg!=null&&!msg.isAsynchronous());}主线程的Thread是什么时候创建的实际上Android主线程(UI线程)并不是通过显式实例化Thread然后调用start()实现的。应用启动时,zygote进程fork出应用进程的时候,这个进程的入口点就是主线程,可以理解为每个进程都有一个默认线程,这个默认线程就是主线程。fork出应用进程之后,会调用ActivityThread.main()方法,此时main方法就是跑在主线程的,然后这里调用Looper.prepareMainLooper()以及Looper.loop()方法。所以这也是为什么在主线程中可以直接实例化Handler的原因。
//这个方法是专门为主线程用的,手动再调用一次会抛异常@DeprecatedpublicstaticvoidprepareMainLooper(){prepare(false);synchronized(Looper.class){if(sMainLooper!=null){thrownewIllegalStateException("ThemainLooperhasalreadybeenprepared.");}sMainLooper=myLooper();}}looper是怎么退出的从loop方法的实现中可以看到,当消息队列next返回空的时候,会退出循环。通过调用Looper实例的quit()或者quitSafely()可以实现将循环退出,方法会设置消息队列的退出标志,并添加一个空消息到消息队列中。再下一次执行next()方法的时候,决定是否要终止循环。同时主线程循环不可以通过调用quit或者quitSafely退出的,这是因为这两个方法最终会调用到MessageQueue的quit方法中,这里会判断如果mQuitAllowed为false的时候,会抛出异常。而mQuitAllowed是在创建MessageQueue的时候传入的,主线程的Looper.prepareMainLooper内调用prepare传参传入的是false,所以主线程不支持退出循环,当应用进程kill的时候循环停止。而我们自己创建的工作线程,我们调用的是Looper.prepare,内部传参是true,所以工作线程支持退出循环。
//给子线程调用的publicstaticvoidprepare(){prepare(true);}privatestaticvoidprepare(booleanquitAllowed){if(sThreadLocal.get()!=null){thrownewRuntimeException("OnlyoneLoopermaybecreatedperthread");}sThreadLocal.set(newLooper(quitAllowed));}//给主线程调用的publicstaticvoidprepareMainLooper(){prepare(false);synchronized(Looper.class){if(sMainLooper!=null){thrownewIllegalStateException("ThemainLooperhasalreadybeenprepared.");}sMainLooper=myLooper();}}quit和quitSafely区别和原理最终会调用到MessageQueue的quit方法
voidquit(booleansafe){if(!mQuitAllowed){thrownewIllegalStateException("Mainthreadnotallowedtoquit.");}synchronized(this){if(mQuitting){return;}mQuitting=true;if(safe){removeAllFutureMessagesLocked();}else{removeAllMessagesLocked();}//WecanassumemPtr!=0becausemQuittingwaspreviouslyfalse.nativeWake(mPtr);}}privatevoidremoveAllMessagesLocked(){Messagep=mMessages;while(p!=null){Messagen=p.next;p.recycleUnchecked();p=n;}mMessages=null;}privatevoidremoveAllFutureMessagesLocked(){finallongnow=SystemClock.uptimeMillis();Messagep=mMessages;if(p!=null){if(p.when>now){removeAllMessagesLocked();}else{Messagen;for(;;){n=p.next;if(n==null){return;}if(n.when>now){break;}p=n;}p.next=null;do{p=n;n=p.next;p.recycleUnchecked();}while(n!=null);}}}从源码上来看,quit()和quitSafely()都是在下一次消息出队的时候决定是否终止循环,正在处理中的消息不会被终止,区别就是
调用quit方法之后,MessageQueue中的mQuitAllowed会置为true,后续调用sendMessage都会返回false
booleanenqueueMessage(Messagemsg,longwhen){if(msg.target==null){thrownewIllegalArgumentException("Messagemusthaveatarget.");}synchronized(this){if(msg.isInUse()){thrownewIllegalStateException(msg+"Thismessageisalreadyinuse.");}if(mQuitting){IllegalStateExceptione=newIllegalStateException(msg.target+"sendingmessagetoaHandleronadeadthread");Log.w(TAG,e.getMessage(),e);msg.recycle();returnfalse;}//...}当消息队列中没有更多消息的时候,会发生什么?当前线程会阻塞在loop()里面的mQueue.next()方法中,MessageQueue的next()方法中也有一个死循环,没有更多消息的时候,会阻塞在这个循环里面。这里不是简单的死循环,所以阻塞不会消耗太大的资源,无消息的时候线程会进入休眠状态,CPU资源会被释放给其他线程使用;当有新消息的时候,线程会被唤醒,继续执行loop
queueIdle实现的时候返回true,则可以监听下一次空闲,如果返回false,这一次回到之后,MessageQueue就会把这个监听从列表中删除,下一次空闲就监听不到了。
publicbooleanpost(Runnableaction){finalAttachInfoattachInfo=mAttachInfo;if(attachInfo!=null){returnattachInfo.mHandler.post(action);}//Postponetherunnableuntilweknowonwhichthreaditneedstorun.//Assumethattherunnablewillbesuccessfullyplacedafterattach.getRunQueue().post(action);returntrue;}可以看到这里有两个分支,当attachInfo不为空的时候走attachInfo.mHandler.post(action);否则走getRunQueue().post(action)
通过对源码View搜索,可以知道attachInfo赋值的时机有两个:attachToWindow赋值;detachedFromWindow置为空
而dispatchAttachedToWindow()是从ViewRootImpl的performTraversals()中调过来的
前面已经解释过,attachInfo不为空的时候,代表View的measure、layout、draw正在执行,或者已经执行完了,此时通过attachInfo.mHandler.post(action)再往主线程post一个任务,必然能拿到宽高
当attachInfo为空的时候,执行的是getRunQueue().post(action),getRunQueue是什么呢?搜索View的源码,我们发现,这是一个任务队列,post(action)即往这个队列中加入一个任务,在ViewdispatchAttachedToWindow()的执行执行这个任务队列中的任务
voiddispatchAttachedToWindow(AttachInfoinfo,intvisibility){mAttachInfo=info;//...//Transferallpendingrunnables.if(mRunQueue!=null){mRunQueue.executeActions(info.mHandler);mRunQueue=null;}//...onAttachedToWindow();//...}executeActions就是把任务post到主线程处理
publicclassHandlerActionQueue{privateHandlerAction[]mActions;privateintmCount;publicvoidpost(Runnableaction){postDelayed(action,0);}publicvoidpostDelayed(Runnableaction,longdelayMillis){finalHandlerActionhandlerAction=newHandlerAction(action,delayMillis);synchronized(this){if(mActions==null){mActions=newHandlerAction[4];}mActions=GrowingArrayUtils.append(mActions,mCount,handlerAction);mCount++;}}//...publicvoidexecuteActions(Handlerhandler){synchronized(this){finalHandlerAction[]actions=mActions;for(inti=0,count=mCount;i