Handler
、
Thread
和
HandlerThread详解
区别:
1)Handler:在Android中负责发送和处理消息,通过它可以实现其他支线线程与主线程之间的消通讯
2)Thread:线程,可以看作是进程的一个实体,是CPU调度和分派的基本单位,他是比进程更小的独立运行的基本单位
3)HandlerThread:封装了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;
}
}