Android HandlerThread源码浅析


/**
* 用于启动具有Looper的新线程的方便类。Looper能够被用于创建Handler。但是类仍然需要调用start()方法,才能开启线程
*/
public class HandlerThread extends Thread {
    int mPriority; //优先级
    int mTid = -1;
    Looper mLooper;//Looper对象,可以用于两个线程之间传递信息

    public HandlerThread(String name) {
        super(name);
        mPriority = Process.THREAD_PRIORITY_DEFAULT;
    }

    /**
     * 构造函数:创建一个带有名称和优先级的HandlerThread   
     */
    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    /**
     * 回调方法,可以被重写,如果需要执行一个Looper的Loop方法
     */
    protected void onLooperPrepared() {
    }

    @Override
    public void run() {
        mTid = Process.myTid();
        Looper.prepare();  //启动一个新的区别于主线程的Looper
        synchronized (this) {
            mLooper = Looper.myLooper(); //获取刚刚新建的Looper
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -1;
    }

    /**
     * 方法返回一个本线程中创建的一个Looper。如果线程没有被启动,或者是isAlive()是false,就返回null。 如果这个线程被启动了,这个方法将会阻塞直到Looper被初始化
     * @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;
    }

    /**
     * 退出该线程的Looper
     */
    public boolean quit() {
        Looper looper = getLooper();
        if (looper != null) {
            looper.quit();
            return true;
        }
        return false;
    }

    /**
     * 安全的退出Looper对象.
     * <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;
    }

    /**
     * 返回线程的id. See Process.myTid().
     */
    public int getThreadId() {
        return mTid;
    }
}

后续还会更新HandlerThread的用法和其他相关知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值