北京市公共资源交易服务平台,seo网站买,怎么做logo网站,网站建设年度计划Handler 、 Thread 和 HandlerThread详解 区别#xff1a; 1#xff09;Handler#xff1a;在Android中负责发送和处理消息#xff0c;通过它可以实现其他支线线程与主线程之间的消通讯 2#xff09;Thread#xff1a;线程#xff0c;可以看作是进程的一个实体#xff… Handler 、 Thread 和 HandlerThread详解 区别 1Handler在Android中负责发送和处理消息通过它可以实现其他支线线程与主线程之间的消通讯 2Thread线程可以看作是进程的一个实体是CPU调度和分派的基本单位他是比进程更小的独立运行的基本单位 3HandlerThread封装了Handler ThreadHandlerThread适合在有需要一个工作线程非UI线程任务的等待队列的形式优点是不会有堵塞 减少了对性能的消耗缺点是不能同时进行多个任务的处理需要等待进行处理。处理效率低可以当成一个轻量级的线程池来用 Handler 实现原理 由 handler、Looper、MessageQueue 三部分组成由handler post( NonNull Runnable r)消息到到MessageQueue 单向链表 而MessageQueue 由Looper 管理做无限的循环取消息队列里面的消息并将消息分给handler处理 当消息一直循环到MessageQueue里没有消息了循环就阻塞相当于结束循环 然后handler 通过回调方法回调消息给 handleMessage(Message msg) 处理 部分源码截图 1.handler 发送消息 2.looper myLooper 获取一个Thread相对应唯一一个looper和looper的构造函数Thread. currentThread() 获取当前代码块被哪个线程调用 MessageQueue一个入队方法enqueueMessage() 方法一个出队方法 详细介绍MessageQueue 参考连接 https://www.sohu.com/a/145311556_675634 HandlerThread 实现 本质就是一个线程Thread,(其中封装Looper ) public class HandlerThread extends Thread { int mPriority; int mTid -1; Looper mLooper; public HandlerThread(String name) { super(name); mPriority Process.THREAD_PRIORITY_DEFAULT; } /** * Constructs a HandlerThread. * param name * param priority The priority to run the thread at. The value supplied must be from * {link android.os.Process} and not from java.lang.Thread. */ public HandlerThread(String name, int priority) { super(name); mPriority priority; } /** * Call back method that can be explicitly overridden if needed to execute some * setup before Looper loops. */ protected void onLooperPrepared() { } Override public void run() { mTid Process.myTid(); Looper.prepare(); synchronized (this) { mLooper Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid -1; } /** * This method returns the Looper associated with this thread. If this thread not been started * or for any reason is isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized. * return The looper. */ 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; } public boolean quit() { Looper looper getLooper(); if (looper ! null) { looper.quit(); return true; } return false; } public boolean quitSafely() { Looper looper getLooper(); if (looper ! null) { looper.quitSafely(); return true; } return false; } /** * Returns the identifier of this thread. See Process.myTid(). */ public int getThreadId() { return mTid; } }