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
  • 相关阅读:
    反射工具类
    序列化反序列化工具类
    开发SCM系统笔记001
    卸载Oracle
    log4j日志级别
    类加载器与methodinterceptor接口
    hibernate 查询、二级缓存、连接池
    Hibernate缓存、组件、继承映射
    Hibernate映射1
    Hibernate配置文件
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3302987.html
Copyright © 2011-2022 走看看