When someone asks you what HandlerThread Yes, please tell him

What HandlerThread that?

A Thread Handler's own?

So understanding the literal meaning is right, but a more precise to say what is contained within the Looper Thread, this can be learned from HandlerThread source comments.

/**
 * 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.
 */

Start a new thread for convenient class has a looper. You can use looper to create a handler class. Note that still must call the start () to start.

To obtain a bound with Handler can () method to obtain built-in getThreadHandler.

public Handler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getLooper());
        }
        return mHandler;
    }

Then, when the moment calls from handlerThread.start () method, which is inside what happened then? Thread the start () method the following is remarked.

/**
 * Causes this thread to begin execution; the Java Virtual Machine
 * calls the <code>run</code> method of this thread.
 */

Cause this thread to begin execution; Java Virtual Machine calls this thread's <code> run </ code> method.

So, go and see HandlerThread the run () method.

@Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

run () method there is no strange thing, first called Looper.prepare () method to create a Looper, then added a synchronization lock acquisition Looper object for the current thread assigned to the mLooper and wake up all the threads, and then set the current thread priority, and then call onLooperPrepared () method, the last call Looper.loop () open cycle.

Some may wonder why should we increase the synchronization lock on assignment mLooper, there will be explained later.

See here, you might think that with our own inheritance open a Looper Thread no different than it was in the run method, indeed, but the official also said HandlerThread class is a convenient, easy to use we Handler child thread.

By the way, the top run () method in the onLooperPrepared () method is doing?

/**
 * Call back method that can be explicitly overridden if needed to execute some
 * setup before Looper loops.
 */
 protected void onLooperPrepared() {
 }

If you need to perform some settings before Looper cycle, this method can be overwritten.

emmm, that run () method Riga synchronization lock is why?

If you do not want to provide us by HandlerThread getThreadHandler () method to obtain a Handler, HandlerThread also provides getLooper () method provides Looper object creation to realize their Handler for you.

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;
    }

This time will understand why the assignment to be completed after mLooper re-awaken in all the threads in the run () method for synchronizing the lock. Because this method blocks thread until the looper is initialized.

HandlerThread whole class also less than 200 lines of code, in addition to those above, it encapsulate method exit Looper thread when not in use.

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;
    }

As can be seen, HandlerThread really is a convenient class ah, cao convenient ah!

HandlerThread usage scenarios

Compared to ordinary Thread, why should I use HandlerThread?

For ordinary Thread, perform again on the end of an instance can not start many times, more than once, if you start with an example, it will throw an IllegalThreadStateException exceptions, these are comments in the source code written in Thread.

/**
 * It is never legal to start a thread more than once.
 * 不止一次启动线程永远不合法
 * In particular, a thread may not be restarted once it has completed execution.
 * 特别是,一旦完成执行,线程可能无法重新启动。
 * @exception  IllegalThreadStateException  if the thread was already started.         
 *             如果线程已经启动将抛出IllegalThreadStateException异常
 */

If I want to frequent operation of the database, large file, to request the network, I would frequently create Thread example calls the start (), or they need to perform a series of serial operation; and HandlerThread comes due Handler, it comes with quite when a task queue, as long as the need for time-consuming operation by Handler send or post to perform a series of operations on the line, no longer need to frequently create a Thread, save resources.

Published 45 original articles · won praise 18 · views 30000 +

Guess you like

Origin blog.csdn.net/Ever69/article/details/96863059