handlerThread generates the background:
Opening Thread sub-threads for time-consuming operations, creating and destroying threads multiple times consumes system resources.
What is handlerThread?
handler + thread + looper
It is actually a thread, but it is different from Thread. It is a thread with a looper inside.
Features of handlerThread:
- It is essentially a thread, which inherits Thread.
- It has its own internal Looper object that can do looper loops.
- By getting the looper object of HandlerThread and passing it to the Handler object, asynchronous tasks can be performed in the handleMessage method .
- The advantage is that it will not block, which reduces the loss of performance. The disadvantage is that it cannot perform multi-task processing at the same time, and needs to wait for processing, and the processing efficiency is low.
- Unlike thread pools that focus on concurrency, HandlerThread is a serial queue [that is, tasks must be executed one by one, and only the next one will be executed after one is executed], and there is only one thread behind HandlerThread.
handlerThread source code analysis:
First paste its complete source code:
/** * 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 { 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; } /** * Quits the handler thread's looper. * <p> * Causes the handler thread's looper to terminate without processing any * more messages in the message queue. * </p><p> * Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. * </p><p class="note"> * Using this method may be unsafe because some messages may not be delivered * before the looper terminates. Consider using {@link #quitSafely} instead to ensure * that all pending work is completed in an orderly manner. * </p> * * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. * * @see #quitSafely */ public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; } /** * Quits the handler thread's looper safely. * <p> * Causes the handler thread's looper to terminate as soon as all remaining messages * in the message queue that are already due to be delivered have been handled. * Pending delayed messages with due times in the future will not be delivered. * </p><p> * Any attempt to post messages to the queue after the looper is asked to quit will fail. * For example, the {@link Handler#sendMessage(Message)} method will return false. * </p><p> * If the thread has not been started or has finished (that is if * {@link #getLooper} returns null), then false is returned. * Otherwise the looper is asked to quit and true is returned. * </p> * * @return True if the looper looper has been asked to quit or false if the * thread had not yet started running. */ 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; } }
The above is its complete source code, which is quite small, but the design is very delicate. Let's take a look at its class annotations:
Among them, it inherits Thread, which is obviously a thread, and then analyzes it:
You can find out by the following code:
Then take a look at the core run() method of the thread:
Finally execute the loop method:
And look at the getLooper() method:
Finally, let's take a look at the methods related to exit:
Among them, the efficiency of safe exit is definitely not as high as that of direct exit.