zoukankan      html  css  js  c++  java
  • HandlerThread实现原理

    HandlerThread继承于Thread类,所以是一个线程类,它存在的价值是什么呢?

    答案就是,HandlerThread可以创建一个自带Looper的线程,自动处理Looper创建时的同步问题

    public class HandlerThread extends Thread {
    
        @Override
        public void run() {
            mTid = Process.myTid();
            Looper.prepare();
            synchronized (this) {
                mLooper = Looper.myLooper();
                notifyAll();
            }
            Process.setThreadPriority(mPriority);
            onLooperPrepared();
            Looper.loop();
            mTid = -1;
        }
    
        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;
        }
    
    }

    关键点就在这两个方法中的synchronized同步块,wait和notifyAll协作使用,保证了mLooper创建的同步。例如,在UI线程中创建了HandlerThread线程对象,并通过getLooper方法获取该线程的Looper,如果mLooper为null,并且线程alive的话,会一直等待直到mLooper实例化结束,自动完成线程同步
    getLooper之前,需要先启动HandlerThread,不然线程处于非启动状态,一直返回空Looper对象。


    原文链接:https://blog.csdn.net/qinhai1989/article/details/82153604

  • 相关阅读:
    【分区】使用 MBR 分区表分区并格式化
    微信小程序公司开发前必读
    Delphi 经典书籍
    sybase 通过select into创建新表
    sybase 创建触发器
    delphi 判断exe重复执行
    git 的诞生
    git 常用命令
    mvn spring-boot:run运行不了的解决办法
    git 提交代码
  • 原文地址:https://www.cnblogs.com/androidxufeng/p/12779390.html
Copyright © 2011-2022 走看看