Android知识Android开发手机移动程序开发

HandlerThread源码解析及使用方法

2017-02-22  本文已影响280人  Big不吃鱼

如何使用HandlerThread?

HandlerThread本质上是一个线程类,继承自Thread类,但是HandlerThread有自己的Looper对象,可以进行looper循环,不断从MessageQueue中取消息。那么,我们如何使用HandlerThread呢?

  1. 创建HandlerThread实例
// 创建HandlerThread的实例,并传入参数来表示当前线程的名字,此处//将该线程命名为“HandlerThread”
private HandlerThread mHandlerThread = new HandlerThread("HandlerThread");
  1. 启动HandlerThread线程
mHandlerThread.start();
  1. 使用HandlerThread的Looper去构建Handler并实现其handlMessage的回调方法
private Handler mHandler;
// 该Callback方法运行于子线程,mHandler在创建时使用的是mHandlerThread的looper对象!!
mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.d("Kathy","Received Message = " + msg.what + "   CurrentThread = " + Thread
                        .currentThread().getName());
            }
        };

可以看出,我们将前面的创建的HandlerThread实例的Looper对象传递给了Handler,这使得该Handler拥有了HandlerThread的Looper对象,通过该Handler发送的消息,都将被发送到该Looper对象的MessageQueue中,且回调方法的执行也是执行在HandlerThread这个异步线程中
值得注意的是,如果在handleMessage()执行完成后,如果想要更新UI,可以用UI线程的Handler发消息给UI线程来更新。

举个Simple的例子

请看以下代码:

/**
 * Created by Kathy on 17-2-21.
 */

public class HandlerThreadActivity extends Activity {

    private HandlerThread mHandlerThread;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 创建HandlerThread实例并启动线程执行
        mHandlerThread = new HandlerThread("HandlerThread");
        mHandlerThread.start();

        // 将mHandlerThread.getLooper()的Looper对象传给mHandler,之后mHandler发送的消息都将在 
        // mHandlerThread这个线程中执行
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.d("Kathy","Received Message = " + msg.what + "   CurrentThread = " + Thread
                        .currentThread().getName());
            }
        };

        //在主线程中发送一条消息
        mHandler.sendEmptyMessage(1);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //在子线程中发送一条消息
                mHandler.sendEmptyMessage(2);
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandlerThread.quit();
    }
}

创建mHandler时传入HandlerThread实例的Looper对象,然后分别在主线程和其他的子线程中发送空消息,猜测handleMessage()中的Log会输出什么?

执行结果如下:

02-21 19:37:30.395 19479-19506/? D/Kathy: Received Message = 1   CurrentThread = HandlerThread
02-21 19:37:30.396 19479-19506/? D/Kathy: Received Message = 2   CurrentThread = HandlerThread

可知,无论是在主线程中发送消息,还是在其他子线程中发送消息,handleMessage()方法都在HandlerThread中执行。

源码角度解析HandlerThread

HandlerThread的源码结构很简单,行数也不多,推荐大家自己去SDK中阅读。

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

在HandlerThread对象的start()方法调用之后,线程被启动,会执行到run()方法,接下来看看,HandlerThread的run()方法都做了什么事情?

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

在run()方法中,执行了Looper.prepare()方法,mLooper保存并获得了当前线程的Looper对象,并通过notifyAll()方法去唤醒等待线程,最后执行了Looper.loop()开启looper循环语句。也就是说,run()方法的主要作用就是完成looper机制的创建。Handler可以获得这个looper对象,并开始异步消息传递了。

接下来看看Handler是如何获得这个Looper对象呢?

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

Handler通过getLooper()方法获取looper对象。该方法首先判断当前线程是否启动?如果没有启动,返回null;如果启动,进入同步语句。如果mLooper为null,代表mLooper没有被赋值,则当前调用线程进入等待阶段。直到Looper对象被创建且通过notifyAll()方法唤醒等待线程,最后才会返回Looper对象。我们看到在run()方法中,mLooper在得到Looper对象后,会发送notifyAll()方法来唤醒等待的线程。

Looper对象的创建在子线程的run()方法中执行,但是调用getLooper()的地方是在主线程中运行,我们无法保证在调用getLooper()时Looper已经被成功创建,所以会在getLooper()中存在一个同步的问题,通过等待唤醒机制解决了同步的问题。

那么,HandlerThread是如何退出的呢?

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

向下调用到Looper的quit()方法

    public void quit() {
        mQueue.quit(false);
    }
    public void quitSafely() {
        mQueue.quit(true);
    }

再向下调用到MessageQueue的quit()方法:

    void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }

可以看到,无论是调用quit()方法还是quitSafely(),最终都将执行到MessageQueue中的quit()方法
quit()方法最终执行的removeAllMessagesLocked()方法,该方法主要是把MessageQueue消息池中所有的消息全部清空,无论是延迟消息(延迟消息是指通过sendMessageDelayed或通过postDelayed等方法发送)还是非延迟消息。

quitSafely()方法,其最终执行的是MessageQueue中的removeAllFutureMessagesLocked方法,该方法只会清空MessageQueue消息池中所有的延迟消息,并将消息池中所有的非延迟消息派发出去让Handler去处理完成后才停止Looper循环,quitSafely相比于quit方法安全的原因在于清空消息之前会派发所有的非延迟消息。最后需要注意的是Looper的quit方法是基于API 1,而Looper的quitSafely方法则是基于API 18的。

上一篇下一篇

猜你喜欢

热点阅读