Android中的HandlerThread分析

HandlerThread简介

HandlerThread,顾名思义,是一个在其内部可以使用Handler的线程,其实本质是HandlerThread线程内部构造了一个Looper环境。源码如下:在其run方法中初始化了一个Looper的环境,创建了Looper对象并且开启了loop循环。

//HandlerThread 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对象的创建与Looper对象的获取使用了同步锁,以及线程的等待唤醒机制,如果HandlerThread线程Looper对象尚未初始化完毕,则外部获取Looper的线程将处于等待状态,直到Looper初始化完成,然后唤醒所有的等待线程,源码如下

//HandlerThread getLooper()方法
 public Looper getLooper() {
        if (!isAlive()) {
            return null;
        }
        
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mLooper == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

因为HandlerThread内部开启了Looper loop方法进行了死循环,所以该线程会一直处于运行状态,不会销毁。所以该线程使用完毕之后我们应该主动调用quit()或者quitSafely()方法退出Looper循环,进而结束线程。

//HandlerThread quit()方法
public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }
//HandlerThread quitSafely()方法
public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

Looper quit()和quitSafely()区别

  • quit(),调用后直接终止Looper,不在处理任何Message,所有尝试把Message放进消息队列的操作都会失败,比如Handler.sendMessage()会返回false,但是存在不安全性,因为有可能有Message还在消息队列中没来的及处理就终止Looper了。
  • quitSafely(),调用后会在所有消息都处理后再终止Looper,所有尝试把Message放进消息队列的操作也都会失败。
Looper退出的原理分析

如下源码所示,loop()里面有一个for循环,只有当MessageQueue的next()返回null的时候才会退出循环终止Handler机制。再看看MessageQueue的next()我们也看到一个for循环,如果有消息的话就把消息返回,没有消息且mQuitting=false的时候继续循环下去,只有当没有消息然后mQuitting=true的时候返回null。根据Looper代码所示Looper.quit()最终会调用MessageQueue.removeAllMessagesLocked()表示直接把消息队列里面的消息清空,而Looper.quitsafely()会调用MessageQueue.removeAllFutureMessagesLocked(),表示把所有延迟消息清除。

//Looper loop()方法
public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;
        ...
        for (;;) {
            Message msg = queue.next(); // might block
            //当msg==null时,会退出loop循环
            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);

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }
            ...
            msg.recycleUnchecked();
        }
    }
//MessageQueue next()方法
Message next() {
        ...
        for (;;) {
            ...
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                //有消息
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (false) Log.v("MessageQueue", "Returning message: " + msg);
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }
                //没有消息并且mQuitting==true,则return null
                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }
                ...
            }
        }
    }
//Looper quit()
public void quit() {
        mQueue.quit(false);
    }
    
//Looper quitSafely()
public void quitSafely() {
        mQueue.quit(true);
    }
    
//MqssageQueue quit(bool safe)方法
void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                //quit()
                removeAllFutureMessagesLocked();
            } else {
                //quitSafely()
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

可以总结到,quit()实际上是把消息队列全部清空,然后让MessageQueue.next()返回null,令Looper.loop()循环结束从而终止Handler机制,但是存在着不安全的地方是可能有些消息在消息队列没来得及处理。而quitsafely()做了优化,只清除消息队列中延迟信息,等待消息队列剩余信息处理完之后再终止Looper循环。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值