带你从源码理解Looper ,handle,MessageQueue,HandleThread

        .网上可能有很多关于Looper ,handle,MessageQueue的文章,这里我不过多解释Looper ,handle、MessageQueue的关系,Looper是负责循坏MessageQueue里面的Messgae的,MessgaeQueue只是个存储Message的一个队列,handle只负责把消息放置到Messagequeue里面,和处理消息。这样讲可能很枯燥,我们从源码去分析这一原理:

       1.对于接触android有段时间android 爱好者可能有这样的疑问,handle处理的消息的为什么会执行在主线程中运行,首先我们从handle创建去分析,看源码
  
public Handler() {
    this(null, false);
}
 
ublic 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(); //获取当前线程的Looper,默认handle在主线程创建,获取是主线程的Looper,在刚开始启动应用的时候默认创建了主线程的Looper(下面会从ActivityThread里面main方法去介绍主线程的Looper的创建)这也是创建handle默认是运行在主线程的原因,下面贴源码向大家详细介绍
    if (mLooper == null) {    //如果在子线程直接创建Looper 会抛出如下错误,子线程默认是没有调用Looper.prepare()创建消息队列,如果要在子线程运行创建handle,必须先创建子线程的Looper
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

在android刚开始启动的时候,会执行Android 里面的找到ActivityThread方法里面main方法 ,相当于java里面的main方法, 进入应用的入口,阅读过源码的工程师可能发现到 ,在main方法里面的 Looper. prepareMainLooper () ;创建了消息队列, Looper.loop()循坏去消息里面的队列,这也是上面讲的handle在主线程创建的时候没有抛出"Can't create handler inside thread that has not called Looper.prepare()"  的原因
      
   
public static void main(String[] args) {
              Looper.prepareMainLooper();  //创建Looper
               ....
              Looper.loop();  //循环消息队列里面的消息
          }

 
public static void prepareMainLooper() {
    prepare(false);
    synchronized (Looper.class) {
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already been prepared.");
        }
        sMainLooper = myLooper();  //创建了主线程的Looper ,直接从Threadlocal里面获取
    }
}
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)); //将Looper存放在ThreadLocal里面,每个线程只能存储一个Looper
}

private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);  //创建了消息队列
    mThread = Thread.currentThread();
}

  在ActivityThread里面的main方法建了Looper
创建了Looper做了些什么 ,其实已经把消息队列创建了, 把对应的Looper存在ThreadLocal 里面,这里需要记住,每个线程只有一个Looper,ThreadLocal是个什么类,Looper会存储在哪里,这里不对ThreadLocal做过多解释,有兴趣的可以继续读源码, 接着介绍下Looper.loop();执行了些什么
  
public static void loop() {
    final Looper me = myLooper(); //获取存储在ThreadLocal里面的Looper
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue; //从Looper里面获取消息队列

    // 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 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); //将消息交给handle处理

        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是通过死循环去取队列的消息,可能你想说的是为什么没有阻塞主线程,只有当消息队列里有消息时,才循坏取消息,当消息队列里没有消息时,会阻塞 在queue.next方法,直到消息队列里面有消息时才会向下执行循坏取消息,取到的消息会通过 msg.target.dispatchMessage(msg)交给了handle处理了消息
     2.为什么handleThread 可以让handle处理子线的消息,这个原理跟上面的一样,handle之所以能处理主线的消息队列,上面已经介绍的很清楚了,handle在主线创建拿到的是主线的Looper,上面分析很清楚了,不过多介绍 ,下面分析下handle处理子线的消息,
workThread = new HandlerThread("work_thread");
workThread.start();
workHandler = new Handler(workThread.getLooper()) {
   @Override
   public void handleMessage(Message msg) {
      super.handleMessage(msg);
      workThreadHandleMessage(msg); // 消息处理
   }
};
workHandler.sendMessage(workHandler.obtainMessage(GlobalDef.WM_ON_CREATE));
上面一段代码是利用handleThread+handle处理子线程消息,下面我们从源码去分析
   workThread.start() ; 会去启动handleThread线程,会执行handleThread里面的run方法,我们分析下run方法做了些什么
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare(); //创建该线程的Looper ,这也就是handle处理消息是在子线程的原因
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop(); //循坏消息队列的消息
    mTid = -1;
}
 从上面源码可以看出handleThread线程启动默认会创建该线程下的Looper,Looper在此线程去循坏消息队列的消息分发给handle处理,这里原来上面Looper.loop源码里面已分析。。。    哈哈哈,写的第一篇博客,好记性不如烂笔头,也是方便自己学习,大家共同进步,如果有什么错误,欢迎大家赐教
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值