Android中的HandlerThread分析_android 怎么判断handlerthread中的线程有没有执行完-程序员宅基地

技术标签: handler  HandlerThread  android  thread  Android筑基  

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循环。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lilinjie_blog/article/details/106850858

智能推荐

JWT(Json Web Token)实现无状态登录_无状态token登录-程序员宅基地

文章浏览阅读685次。1.1.什么是有状态?有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,典型的设计如tomcat中的session。例如登录:用户登录后,我们把登录者的信息保存在服务端session中,并且给用户一个cookie值,记录对应的session。然后下次请求,用户携带cookie值来,我们就能识别到对应session,从而找到用户的信息。缺点是什么?服务端保存大量数据,增加服务端压力 服务端保存用户状态,无法进行水平扩展 客户端请求依赖服务.._无状态token登录

SDUT OJ逆置正整数-程序员宅基地

文章浏览阅读293次。SDUT OnlineJudge#include<iostream>using namespace std;int main(){int a,b,c,d;cin>>a;b=a%10;c=a/10%10;d=a/100%10;int key[3];key[0]=b;key[1]=c;key[2]=d;for(int i = 0;i<3;i++){ if(key[i]!=0) { cout<<key[i.

年终奖盲区_年终奖盲区表-程序员宅基地

文章浏览阅读2.2k次。年终奖采用的平均每月的收入来评定缴税级数的,速算扣除数也按照月份计算出来,但是最终减去的也是一个月的速算扣除数。为什么这么做呢,这样的收的税更多啊,年终也是一个月的收入,凭什么减去12*速算扣除数了?这个霸道(不要脸)的说法,我们只能合理避免的这些跨级的区域了,那具体是那些区域呢?可以参考下面的表格:年终奖一列标红的一对便是盲区的上下线,发放年终奖的数额一定一定要避免这个区域,不然公司多花了钱..._年终奖盲区表

matlab 提取struct结构体中某个字段所有变量的值_matlab读取struct类型数据中的值-程序员宅基地

文章浏览阅读7.5k次,点赞5次,收藏19次。matlab结构体struct字段变量值提取_matlab读取struct类型数据中的值

Android fragment的用法_android reader fragment-程序员宅基地

文章浏览阅读4.8k次。1,什么情况下使用fragment通常用来作为一个activity的用户界面的一部分例如, 一个新闻应用可以在屏幕左侧使用一个fragment来展示一个文章的列表,然后在屏幕右侧使用另一个fragment来展示一篇文章 – 2个fragment并排显示在相同的一个activity中,并且每一个fragment拥有它自己的一套生命周期回调方法,并且处理它们自己的用户输_android reader fragment

FFT of waveIn audio signals-程序员宅基地

文章浏览阅读2.8k次。FFT of waveIn audio signalsBy Aqiruse An article on using the Fast Fourier Transform on audio signals. IntroductionThe Fast Fourier Transform (FFT) allows users to view the spectrum content of _fft of wavein audio signals

随便推点

Awesome Mac:收集的非常全面好用的Mac应用程序、软件以及工具_awesomemac-程序员宅基地

文章浏览阅读5.9k次。https://jaywcjlove.github.io/awesome-mac/ 这个仓库主要是收集非常好用的Mac应用程序、软件以及工具,主要面向开发者和设计师。有这个想法是因为我最近发了一篇较为火爆的涨粉儿微信公众号文章《工具武装的前端开发工程师》,于是建了这么一个仓库,持续更新作为补充,搜集更多好用的软件工具。请Star、Pull Request或者使劲搓它 issu_awesomemac

java前端技术---jquery基础详解_简介java中jquery技术-程序员宅基地

文章浏览阅读616次。一.jquery简介 jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互 jQuery 的功能概括1、html 的元素选取2、html的元素操作3、html dom遍历和修改4、js特效和动画效果5、css操作6、html事件操作7、ajax_简介java中jquery技术

Ant Design Table换滚动条的样式_ant design ::-webkit-scrollbar-corner-程序员宅基地

文章浏览阅读1.6w次,点赞5次,收藏19次。我修改的是表格的固定列滚动而产生的滚动条引用Table的组件的css文件中加入下面的样式:.ant-table-body{ &amp;amp;::-webkit-scrollbar { height: 5px; } &amp;amp;::-webkit-scrollbar-thumb { border-radius: 5px; -webkit-box..._ant design ::-webkit-scrollbar-corner

javaWeb毕设分享 健身俱乐部会员管理系统【源码+论文】-程序员宅基地

文章浏览阅读269次。基于JSP的健身俱乐部会员管理系统项目分享:见文末!

论文开题报告怎么写?_开题报告研究难点-程序员宅基地

文章浏览阅读1.8k次,点赞2次,收藏15次。同学们,是不是又到了一年一度写开题报告的时候呀?是不是还在为不知道论文的开题报告怎么写而苦恼?Take it easy!我带着倾尽我所有开题报告写作经验总结出来的最强保姆级开题报告解说来啦,一定让你脱胎换骨,顺利拿下开题报告这个高塔,你确定还不赶快点赞收藏学起来吗?_开题报告研究难点

原生JS 与 VUE获取父级、子级、兄弟节点的方法 及一些DOM对象的获取_获取子节点的路径 vue-程序员宅基地

文章浏览阅读6k次,点赞4次,收藏17次。原生先获取对象var a = document.getElementById("dom");vue先添加ref <div class="" ref="divBox">获取对象let a = this.$refs.divBox获取父、子、兄弟节点方法var b = a.childNodes; 获取a的全部子节点 var c = a.parentNode; 获取a的父节点var d = a.nextSbiling; 获取a的下一个兄弟节点 var e = a.previ_获取子节点的路径 vue

推荐文章

热门文章

相关标签