• Android(八) HandlerThread


    1.Looper

      Looper used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create

    one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.

    2.HandlerThread 为我们解决问题

      Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start()

    must still be called.

    public class HandlerThread extends Thread {
       
        Looper mLooper;
    
        protected void onLooperPrepared() {
        }
    
        public void run() {
            mTid = Process.myTid();
            Looper.prepare();
            synchronized (this) {
                mLooper = Looper.myLooper();
                notifyAll();            //为mLooper赋值,唤醒等待的线程
            }
            Process.setThreadPriority(mPriority);
            onLooperPrepared();
            Looper.loop();
            mTid = -1;
        }
       
        public Looper getLooper() {
            if (!isAlive()) {                 //线程是否启动
                return null;
            }
            
            synchronized (this) {
                while (isAlive() && mLooper == null) {
                    try {
                        wait();                 // 如果mLooper为null则等待
                    } catch (InterruptedException e) {
                    }
                }
            }
            return mLooper;
        } 
    }

    3.使用HandlerThread

          HandlerThread thread = new HandlerThread("handlerThread");
          thread.start();
    
          Looper looper = thread.getLooper();                         
          Handler handler = new ServiceHandler(looper);         //传入Looper参数,初始化Handler
  • 相关阅读:
    Docker数据卷
    Hyperloglog算法
    Greenplum6.9集群安装文档
    Java实现线程间通信方式
    计算机存储管理方式
    greenplum6.9踩坑总结
    Linux 内核参数Overcommit_memory(最近生产中Airflow和Greenplum有被这个参数坑到......)
    Airflow概念
    airflow安装文档
    基于Docker进行Zookeeper集群的安装
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3302987.html
Copyright © 2020-2023  润新知