HandlerThread源码阅读

HandlerThread一眼看上去,就知道这应该是针对Handler机制的一个Thread。由于代码较短,流程较少。先把源码全都放出来。

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

* Causes the handler thread's looper to terminate without processing any * more messages in the message queue. *

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

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

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

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

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

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

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

按步骤阅读源码,类说明。

带有一个Looper的非常方便的用于创建一个新的线程的类,这个Looper用于创建Handler类。但是呢在创建Handler之前,必须先调用HandlerThread的start方法。

成员变量

    int mPriority;
    int mTid = -1;
    Looper mLooper;

一个是线程的优先级,一个是一个Id,最后是一个Looper。Handler既然是对Handler和Thread的封装,肯定需要不断地处理Handler的消息。我们知道Looper是不断地从消息队列取出消息给Handler的。我们在主线程使用Handler的时候,并不需要对Looper做任何的操作,其实是主线程隐藏了这些操作。HandlerTHread一样地隐藏了这些操作。

我们来看构造函数

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

并没有任何的特别仅仅是创建线程并设置线程的优先级而已。

既然是线程run方法是关键。

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

这里创建了Looper对象,并且开启了Looper的消息机制(不断地监听MessageQueue中是否有消息,然后取出来给Handler去处理)。由于Looper是一个死循环,所以该run方法也是一个死循环。想要结束HandlerThread就必须退出Looper,这里HandlerThread封装好了两个方法。

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

然后就没有了?确实是这样,你可能会问Handler是如实现在HandlerThread中运行的。一般的要运行在Thread中的操作都应该在run中调用的,这里并没有看到,调用Handler的handleMessage方法。OK,其实了解Handler机制的应该知道:Looper的loop方法是不断地取出消息,然后调用了Handler的dispatchMassage方法,该方法就是处理Handler消息的。由于在HandlerThread的run方法中调用了Looper.loop()方法,所以便将Handler的handleMassage方法运行在HandlerThread中了。

你可能感兴趣的:(HandlerThread源码阅读)