Android并发编程之Handler,MessageQueue,Looper详解

本文详细介绍了Handler、Looper和MessageQueue之间的关系及其在Android线程通信中的作用。通过实例讲解了如何配置线程的Looper和MessageQueue,以及如何避免内存泄露。同时阐述了主线程与工作线程间的消息传递,强调了在不再需要时调用Looper.quit的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Handler和Looper,MessageQueue之间是什么关系?

Looper和MessageQueue是线程中的概念,但是线程默认是没有Looper和MessageQueue的,我们需要手动去设置他们,当一个线程有了Looper和MessageQueue后,就可以关联一个Handler,我们再通过这个Handler,就可以从别的线程中发送消息给这个线程来执行。

我们给一个线程配置了Looper和MessageQueue后,当有消息通过Handler发送到本线程后,就会加入到MessageQueue中,然后Looper会不断的循环从MessageQueue中取出消息,然后放到Handler的handleMessage()中去执行。

如何给一个线程配置一个Looper和MessageQueue

给一个线程配置一个Looper和MessageQueue很简单,只需要调用Looper.prepare()和Looper.loop()就可以了。
首先我们先来看一下Looper.prepare()中都做了什么

 /** 
     *当我们调用了prepare后,我们就给这个线程配置了一个Looper,然后调用
     *loop()方法后会创建MessageQueue并且looper会进入无限循环来从消息
     *队列中取出消息去处理,我们调用quit()方法可以使looper结束这个无限
     *循环
      */
    public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        //ThreadLocal是线程本地存储,每个线程的ThreadLocal中存的数据
        //都是不一样的,他们只属于本线程,当我们为该线程创建了一个Looper
        //之后,将这个Looper存储到ThreadLocal中,一个线程只能有一
        //个Looper,如果再次调用prepare方法的话,就会抛出异常
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //new出了一个Looper
        sThreadLocal.set(new Looper(quitAllowed));
    }

再来看一下Looper.loop()方法中做了什么

/**
     * 当调用了loop方法后,Looper会无限循环从MessageQueue中取出消息,
     * 因此我们一定要调用quit()来退出循环
     */
    public static void loop() {
        //获取当前线程的Looper
        final Looper me = myLooper();
        if (me == null) {
            //如果没有调用Loop.prepare()的话,就会抛出下面这个异常
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //创建一个MessageQueue
        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.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        //无限循环
        for (;;) {
            //从MessageQueue中取出消息
            Message msg = queue.next(); // might block
            if (msg == null) {
                // 没有消息,说明消息队列已经退出了,因此跳出循环
                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就是与此线程关联的Handler对象,
            //dispatchMessage方法将msg交给Handler去处理
            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已经交给Handler去处理,这里将msg复位
            msg.recycleUnchecked();
        }
    }

我们看到从MessageQueue取出的消息会调用Handler的dispatchMessage方法去执行,我们看看dispatchMessage做了什么事情

 /**
     * Handle system
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值