zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    关于面试总结8-http协议相关面试题
    关于面试总结7-linux篇
    关于面试总结6-SQL经典面试题
    关于面试总结5-python笔试题(递归)
    关于面试总结4-python笔试题
    关于面试总结3-SQL查询
    关于面试总结2-SQL学生表
    关于面试总结1-SQL学生表
    浅谈多变量线性回归中的数据规范化
    浅谈KL散度
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3302987.html
Copyright © 2011-2022 走看看