Android多线程(1)之HandlerThread学习

HandlerThread谷歌给的官方说明:

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

意思是:一个方便开启的带有looper的线程的类,looper可以用于创建handler类,注意在使用looper创建handler之前,必须调用了start()方法

我们来分析一下源码:

public class HandlerThread extends Thread

他是thread的一个子类,我们来看HandlerThread的结构

这里写图片描述

这个类重写了Thread的run方法,但是没有重写start方法,说明HandlerThread调用的是Thread的原生方法。
我们来看run方法源码:

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

代码的作用:
1、是对Looper进行操作,创建looper: Looper.prepare();
2、设置线程优先级 :Process.setThreadPriority(mPriority);默认优先级
3、开启looper循环,直到调用looper.quite方法。

通过上面源代码分析我们应该明白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;
    }

发现问题没有:没有带有Runnable的构造器,所以,这个类不是让我们自己实现run方法的,因为在run方法中我们调用了looper.loop();方法,进入了死循环,所以,我们不能自己去实现run方法了。

总结:HandlerThread就是一个带有looper的类,我们可以使用handler,让msg在handlerThread开启的线程中执行,方便我们做定时任务,并发要求不高的任务,不用平凡的开启线程了,使用HandlerThread就行。

猜你喜欢

转载自blog.csdn.net/liujian8654562/article/details/80476393