Android handlerThread并发了解

news/2024/7/5 3:25:59

Android开发中如何实现并发,参考HandlerThread代码

核心是由synchronized 配合 wait、notifyall进行处理并发

HandlerThread.java

public class HandlerThread extends Thread {
	//优先级
    int mPriority;
    int mTid = -1;
    Looper mLooper;
    private @Nullable Handler mHandler;

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }
    
    /**
     * Constructs a HandlerThread.
     * @param name
     * @param priority The priority to run the thread at. The value supplied must be from 
     * {@link android.os.Process} and not from java.lang.Thread.
     */
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }
    
    /**
     * Call back method that can be explicitly overridden if needed to execute some
     * setup before Looper loops.
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        //创建的线程的Looper,首先进行prepare操作
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            //唤醒由 getLooper函数导致处于wait状态的线程
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        //开始轮训处理message
        Looper.loop();
        mTid = -1;
    }
    
    /**
     * This method returns the Looper associated with this thread. If this thread not been started
     * or for any reason isAlive() returns false, this method will return null. If this thread
     * has been started, this method will block until the looper has been initialized.  
     * @return The looper.
     */
    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) {
            	//如果没有拿到mLooper,则进行等待notifyAll();
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mLooper;
    }

    /**
     * @return a shared {@link Handler} associated with this thread
     * @hide
     */
    @NonNull
    public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

    /**
     * Quits the handler thread's looper.
     * <p>
     * Causes the handler thread's looper to terminate without processing any
     * more messages in the message queue.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p class="note">
     * Using this method may be unsafe because some messages may not be delivered
     * before the looper terminates.  Consider using {@link #quitSafely} instead to ensure
     * that all pending work is completed in an orderly manner.
     * </p>
     *
     * @return True if the looper looper has been asked to quit or false if the
     * thread had not yet started running.
     *
     * @see #quitSafely
     */
    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    /**
     * Quits the handler thread's looper safely.
     * <p>
     * Causes the handler thread's looper to terminate as soon as all remaining messages
     * in the message queue that are already due to be delivered have been handled.
     * Pending delayed messages with due times in the future will not be delivered.
     * </p><p>
     * Any attempt to post messages to the queue after the looper is asked to quit will fail.
     * For example, the {@link Handler#sendMessage(Message)} method will return false.
     * </p><p>
     * If the thread has not been started or has finished (that is if
     * {@link #getLooper} returns null), then false is returned.
     * Otherwise the looper is asked to quit and true is returned.
     * </p>
     *
     * @return True if the looper looper has been asked to quit or false if the
     * thread had not yet started running.
     */
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }
}

synchronized原理问题

https://blog.csdn.net/weixin_42460087/article/details/126474481


http://lihuaxi.xjx100.cn/news/1570291.html

相关文章

虚拟机安装 centos

title: 虚拟机安装 centos createTime: 2020-12-13 12:00:27 updateTime: 2020-12-13 12:00:27 categories: linux tags: 虚拟机安装 centos 路线图 主机(宿主机) —> centos --> docker --> docker 镜像 --> docker 容器 — docker 服务 1.前期准备 一台 主机 或…

C++项目 Boost搜索引擎

选取boost库官网中的一个网页作为根目录&#xff0c;用它来建立索引。用户在搜索引擎首页搜索&#xff0c;搜索关键字在服务端&#xff08;searcher)进行分词&#xff0c;查找index&#xff08;供系统进行查找索引&#xff09;。 使用单例模式&#xff0c;只有一个index对象。…

软件测试笔试

作者&#xff1a;爱塔居 专栏&#xff1a;软件测试 文章简介&#xff1a;记录了我在笔试、面试过程中遇见的一些小问题 1.软件的生命周期&#xff1a;需求分析、计划、设计、编码、测试、运行维护 2.软件测试的生命周期&#xff1a;需求分析、测试计划、测试设计/开发、测试执…

[论文分享] How to Better Utilize Code Graphs in Semantic Code Search?

How to Better Utilize Code Graphs in Semantic Code Search? [ESEC/FSE 2022] 语义代码搜索极大地促进了软件的重用&#xff0c;使用户能够找到与用户指定的自然语言查询高度匹配的代码片段。由于代码图(如控制流图和程序依赖图)丰富的表达能力&#xff0c;两种主流的研究工…

Nature Communications | 张阳课题组:端到端深度学习实现高精度RNA结构预测

RNA分子是基因转录的主要执行者&#xff0c;也是细胞运作的隐形功臣。它们在基因表达调控、支架构建以及催化活性等多个生命过程中都扮演着关键角色。虽然RNA如此重要&#xff0c;但由于实验数据的缺乏&#xff0c;准确预测RNA 的三维空间结构仍然是目前计算生物学面临的重大挑…

react的1.函数组件2.usestate3.useeffect4.ref5.fragment6.contex 代码加注释

React是一种流行的JavaScript库&#xff0c;用于构建用户界面。它提供了许多有用的功能&#xff0c;其中包括函数组件、useState、useEffect、ref、fragment和context。在本文中&#xff0c;我们将深入探讨这些功能&#xff0c;并提供代码示例和注释。 1.函数组件 函数组件是…

Centos7中如何打开和关闭防火墙??CentOS 7以上默认使用firewall作为防火墙改为iptables

1 防火墙系统为firewall的关闭和打开方式 Centos 7中默认的linux的系统默认防火墙不是iptables,而是firewall,此时应该使用以下方式关闭防火墙了。 &#xff08;1&#xff09;关闭防火墙 systemctl stop firewalld.service #停止firewall systemctl disable firewalld.servi…

大功率PID控温

#include "rtthread.h" #ifdef FRYER_TEMP_PID //PID控温 #include "pid.h" #include "string.h"#define DBG_TAG "app.pid" #define DBG_LVL DBG_INFO #include <rtdbg.h>/** * PID运算. * U(k)KP*[E(k)-E(k-1)]KI*E(k…