为了账号安全,请及时绑定邮箱和手机立即绑定

HandlerThread getLooper()阻塞问题

getLooper()阻塞住了线程,这个子线程还怎么去跑run中的代码去prepare  之类等等。

正在回答

2 回答

这个跟message有什么关系?looper实例都还没有,哪里来的Message?




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

    }


如果在getLooper()并且run()还没有运行起来,这个时候wait()了,阻塞了,然后这个线程还怎么去返过来执行run()。我问的是这个


0 回复 有任何疑惑可以回复我~
#1

慕粉3126759

这个wait()堵塞的是调用thread.looper()函数的主线程。。。事实上你理解错了什么是子线程,只有子线程run()函数中的过程才属于子线程,thread.loop()是在主线程中调用的,属于在主线程中执行,因此waiit()堵塞的是调用wait()方法的主线程. 等到handlerthread的looper实例化以后,主线程就被notifyall()唤醒了
2016-11-03 回复 有任何疑惑可以回复我~

messagequeue为空的时候才会阻塞,不为空的时候是不会阻塞的。

0 回复 有任何疑惑可以回复我~
#1

Jannina 提问者

// If the thread has been started, wait until the looper has been created.
2016-03-04 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Android面试常客Handler详解
  • 参与学习       54885    人
  • 解答问题       183    个

学Android开发,必学Handler,也是Android面试常客

进入课程

HandlerThread getLooper()阻塞问题

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信