Looper.loop()为什么不会阻塞主线程?

今天看IntentService时看到了Thread的run方法如下:

@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

代码Looper.loop()是一个for死循环,然后突然想到主线程中也有Looper为什么不卡主线程于是找到了ActivityThread的源码

public static void main(String[] args) {    

      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();         throw new RuntimeException("Main thread loop unexpectedly exited");    

}

main方法的退出就是Looper.loop();的执行完毕,所有事件都是Looper的监听,主线程本事就是个阻塞。

Android是事件驱动,Looper内部是一个while死循华,只有程序退出后循环才会停止,如果Looper使用中死掉了,任何事件都不会有反应了。事件只会阻塞Looper,而Looper不会阻塞事件。

 

你可能感兴趣的:(android,中级)