HandlerThread

说起HandlerThread我的确没怎么用到过,以至于面试的时候被面试官问起时也是完全不知道。所以,今天就来补一补这个东西。其实这个类也不大,就149行代码。下面就这英文看下意思,当然如果觉得英文烦躁,可以去掉英文就着我蹩脚的翻译暂且看看:


/** 开启一个带有looper的线程,start()方法必须调用(开启线程肯定得调用start()方法啊!)。
 * 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;//获取调用进程的线程ID
    Looper mLooper;//Looper对象

    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.
     */
     //构造函数:传入一个String 对象做线程的名字,一个int值代表线程优先级。
    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.
     */
     //可以重写这个函数做一些准备工作,这个放方法在loop()方法调用之前调用。
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();
        synchronized (this) {
            mLooper = Looper.myLooper();
            //唤醒在等待的
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        //在loop()方法调用之前调用
        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 {
                    //如果Looper未创建好,就先等待,对应上面的notifyAll();
                    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
     */
     //直接退出,调用了looper.quit()方法;
    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.
     */
     //安全退出,调用了quitSafely()方法
    public boolean quitSafely() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quitSafely();
            return true;
        }
        return false;
    }

    /**
     * Returns the identifier of this thread. See Process.myTid().
     */
     //返回Process.myTid()
    public int getThreadId() {
        return mTid;
    }
}
大体意思:

在一个线程中创建了一个Looper对象,而我们知道Looper对象是消息机制的核心。那我们在子线程中弄这样一个Looper对象就意味着该子线程也能像UI线程那样,通过Handle进行线程之间的切换工作,从某个线程切换到该子线程中来。

那么,它到底有什么好处呢?

场景

我们来想一个场景,如果我们现在需要请求网络数据(假设需要请求一张图片,图片请求返回后需要更新UI),我们都知道UI线程中不允许进行耗时的网络请求。那么,我们通常会开启一个子线程来进行请求:如果你不用网络请求的三方库,一般会通过new Thread。然后start()来完成吧!这样的话,如果有多次请求图片,那么我们就得new 很多个Thread。所以这是个问题!!!

现在你就会想,难道(柯南BGM)你是说。。。没错,HandlerThread可以用来解决这个问题。还有这种骚操作?

问题解决分析

通过上面代码我们知道:HandlerThread一个子线程,并且含有一个Looper。
再来看看那个问题:我们之所以需要new Thread。。然后start().是因为UI线程无法进行网络请求,但是,HandlerThread可是一个子线程。。。重要的说三遍。所以,在它里面可以直接请求网络,于是上面的new Thread 。。 start()问题就解决了。(卧槽。。。这也是骚操作?)。
当然,就凭他是个子线程还没法说服我,虽然它是一个子线程不需要new Thread(),但是它自己也可能需要多次创建啊!只不过是从new一个Thread变成了new HanderThread而已。这还不是没卵用。(这这这。。。)

那么如何解释它不需要重复创建呢?
其实也不难,只需要子线程不结束不就行了。(run方法中加个while(true)啊,呵呵),不过,它这里并不是while(true),而是用到了调用了一个loop()方法。

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

loop方法是阻塞的,所以它后面的语句在它未退出的(可以通过quit()方法和quitSafely()方法退出)时候是没办法执行的。再加上它可以通过在外部实现一个Handler,然后,通过这个Handler给Looper发送message,近而源源不断的实现网络请求。所以,这就真正的解决了上面提出的那个问题。(我墙都不服。。。)

这里给一个连接,里面介绍了如何在外部创建一个Handler,然后源源不断进行网络请求。
链接地址:Android 多线程之HandlerThread 完全详解

总结一下优缺点:

引用一篇文章:

作者:Cooke_
链接:http://www.jianshu.com/p/e9b2c0831b0d
來源:简书

  1. HandlerThread将loop转到子线程中处理,说白了就是将分担MainLooper的工作量,降低了主线程的压力,使主界面更流畅。
  2. 开启一个线程起到多个线程的作用。处理任务是串行执行,按消息发送顺序进行处理。
  3. 相比多次使用new Thread(){…}.start()这样的方式节省系统资源。
  4. 但是由于每一个任务都将以队列的方式逐个被执行到,一旦队列中有某个任务执行时间过长,那么就会导致后续的任务都会被延迟处理。
  5. HandlerThread拥有自己的消息队列,它不会干扰或阻塞UI线程。
  6. 通过设置优先级就可以同步工作顺序的执行,而又不影响UI的初始化;
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值