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
  • 相关阅读:
    几种常用类的学习
    类,接口
    方法
    数组使用
    条件控制与循环
    类型转换,运算符
    Java基本类型
    SVN基本使用
    【转】MySQL的btree索引和hash索引的区别
    常用命令(java、linux)
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3302987.html
Copyright © 2011-2022 走看看