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

智能推荐

python简易爬虫v1.0-程序员宅基地

文章浏览阅读1.8k次,点赞4次,收藏6次。python简易爬虫v1.0作者:William Ma (the_CoderWM)进阶python的首秀,大部分童鞋肯定是做个简单的爬虫吧,众所周知,爬虫需要各种各样的第三方库,例如scrapy, bs4, requests, urllib3等等。此处,我们先从最简单的爬虫开始。首先,我们需要安装两个第三方库:requests和bs4。在cmd中输入以下代码:pip install requestspip install bs4等安装成功后,就可以进入pycharm来写爬虫了。爬

安装flask后vim出现:error detected while processing /home/zww/.vim/ftplugin/python/pyflakes.vim:line 28_freetorn.vim-程序员宅基地

文章浏览阅读2.6k次。解决方法:解决方法可以去github重新下载一个pyflakes.vim。执行如下命令git clone --recursive git://github.com/kevinw/pyflakes-vim.git然后进入git克降目录,./pyflakes-vim/ftplugin,通过如下命令将python目录下的所有文件复制到~/.vim/ftplugin目录下即可。cp -R ...._freetorn.vim

HIT CSAPP大作业:程序人生—Hello‘s P2P-程序员宅基地

文章浏览阅读210次,点赞7次,收藏3次。本文简述了hello.c源程序的预处理、编译、汇编、链接和运行的主要过程,以及hello程序的进程管理、存储管理与I/O管理,通过hello.c这一程序周期的描述,对程序的编译、加载、运行有了初步的了解。_hit csapp

18个顶级人工智能平台-程序员宅基地

文章浏览阅读1w次,点赞2次,收藏27次。来源:机器人小妹  很多时候企业拥有重复,乏味且困难的工作流程,这些流程往往会减慢生产速度并增加运营成本。为了降低生产成本,企业别无选择,只能自动化某些功能以降低生产成本。  通过数字化..._人工智能平台

electron热加载_electron-reloader-程序员宅基地

文章浏览阅读2.2k次。热加载能够在每次保存修改的代码后自动刷新 electron 应用界面,而不必每次去手动操作重新运行,这极大的提升了开发效率。安装 electron 热加载插件热加载虽然很方便,但是不是每个 electron 项目必须的,所以想要舒服的开发 electron 就只能给 electron 项目单独的安装热加载插件[electron-reloader]:// 在项目的根目录下安装 electron-reloader,国内建议使用 cnpm 代替 npmnpm install electron-relo._electron-reloader

android 11.0 去掉recovery模式UI页面的选项_android recovery 删除 部分菜单-程序员宅基地

文章浏览阅读942次。在11.0 进行定制化开发,会根据需要去掉recovery模式的一些选项 就是在device.cpp去掉一些选项就可以了。_android recovery 删除 部分菜单

随便推点

echart省会流向图(物流运输、地图)_java+echart地图+物流跟踪-程序员宅基地

文章浏览阅读2.2k次,点赞2次,收藏6次。继续上次的echart博客,由于省会流向图是从echart画廊中直接取来的。所以直接上代码<!DOCTYPE html><html><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /&_java+echart地图+物流跟踪

Ceph源码解析:读写流程_ceph 发送数据到其他副本的源码-程序员宅基地

文章浏览阅读1.4k次。一、OSD模块简介1.1 消息封装:在OSD上发送和接收信息。cluster_messenger -与其它OSDs和monitors沟通client_messenger -与客户端沟通1.2 消息调度:Dispatcher类,主要负责消息分类1.3 工作队列:1.3.1 OpWQ: 处理ops(从客户端)和sub ops(从其他的OSD)。运行在op_tp线程池。1...._ceph 发送数据到其他副本的源码

进程调度(一)——FIFO算法_进程调度fifo算法代码-程序员宅基地

文章浏览阅读7.9k次,点赞3次,收藏22次。一 定义这是最早出现的置换算法。该算法总是淘汰最先进入内存的页面,即选择在内存中驻留时间最久的页面予以淘汰。该算法实现简单,只需把一个进程已调入内存的页面,按先后次序链接成一个队列,并设置一个指针,称为替换指针,使它总是指向最老的页面。但该算法与进程实际运行的规律不相适应,因为在进程中,有些页面经常被访问,比如,含有全局变量、常用函数、例程等的页面,FIFO 算法并不能保证这些页面不被淘汰。这里,我_进程调度fifo算法代码

mysql rownum写法_mysql应用之类似oracle rownum写法-程序员宅基地

文章浏览阅读133次。rownum是oracle才有的写法,rownum在oracle中可以用于取第一条数据,或者批量写数据时限定批量写的数量等mysql取第一条数据写法SELECT * FROM t order by id LIMIT 1;oracle取第一条数据写法SELECT * FROM t where rownum =1 order by id;ok,上面是mysql和oracle取第一条数据的写法对比,不过..._mysql 替换@rownum的写法

eclipse安装教程_ecjelm-程序员宅基地

文章浏览阅读790次,点赞3次,收藏4次。官网下载下载链接:http://www.eclipse.org/downloads/点击Download下载完成后双击运行我选择第2个,看自己需要(我选择企业级应用,如果只是单纯学习java选第一个就行)进入下一步后选择jre和安装路径修改jvm/jre的时候也可以选择本地的(点后面的文件夹进去),但是我们没有11版本的,所以还是用他的吧选择接受安装中安装过程中如果有其他界面弹出就点accept就行..._ecjelm

Linux常用网络命令_ifconfig 删除vlan-程序员宅基地

文章浏览阅读245次。原文链接:https://linux.cn/article-7801-1.htmlifconfigping &lt;IP地址&gt;:发送ICMP echo消息到某个主机traceroute &lt;IP地址&gt;:用于跟踪IP包的路由路由:netstat -r: 打印路由表route add :添加静态路由路径routed:控制动态路由的BSD守护程序。运行RIP路由协议gat..._ifconfig 删除vlan