源码分析:为什么子线程中执行 new Handler() 会抛出

2019-02-14  本文已影响294人  Android平头哥

前言

Handler是我们日常开发中经常要用到的,不管你是新手还是老鸟。刚入行的人可能仅仅知道点用Handler来更新UI等等。记得刚毕业的时候,第一次会用Handler实现了UI的更新,之后的时间对Handler的认识也仅仅是停留在表面功夫,大部分都是临时抱佛脚,碰到问题才想到要去研究源码。

有时候想想,学习动力真的很重要!如果你浮在表面,觉得自己知道怎么用api了,就沾沾自喜,那样永远都不会进步。这个时候就是考验自己的时候了,当你沉下心来,一段源码一段源码的去扣,直到理解为止,在阅读源码的过程中你的思维能力也得到了一次锻炼,我相信,你对这部分知识的理解也会更加透彻。

抛出我们今天的问题:为什么在子线程中执行 new Handler() 会抛出异常?我们先来看看一个小栗子:

 new Thread(new Runnable() {
      @Override
      public void run() {
        new Handler(){
          @Override
          public void handleMessage (Message message){
            super.handleMessage(message);
          }
        };
      }
    },"ThreadOne").start();

运行一下代码,发现程序出现了如下异常:

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:204)
        at android.os.Handler.<init>(Handler.java:118)
        at com.example.bthvi.myconstrainlayoutapplication.MainActivity$1$1.<init>(MainActivity.java:21)
        at com.example.bthvi.myconstrainlayoutapplication.MainActivity$1.run(MainActivity.java:21)
        at java.lang.Thread.run(Thread.java:764)

嗯,这就是我们今天要讨论的问题:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare(),大致的意思是无法在未调用looperation .prepare()的线程中创建handler,要找到原因,从Handler的构造方法开始

Handler构造方法
当我们new Handler()的时候,最终调用了Handler的以下方法

 /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
public Handler() {
        this(null, false);
}
    
   
public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }
        // 标记1
        mLooper = Looper.myLooper();  
        if (mLooper == null) {
        //  标记2
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

翻译一下这段注释:默认的构造函数将handler和当前线程所持有的Looper关联在一起,没有当前线程没有Looper对象,handler就无法接收消息,异常也就被抛出了。我们接在往下看,if判断语句里的boolean型变量默认值为false,所以里面的逻辑暂时先不看。接下来程序走到了 标记1所对应的语句处,我们看一下源码:

/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

看一下注释,大致的意思是返回与当前thread相关联的Looper对象,如果当前thread没有关联的Looper那就返回null。 我们直接看sThreadLocal.get()源码:

/**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

该方法第二行调用了getMap(t)方法,我们来看看getMap(t)的源码:

/**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

getMap(t)返回一个ThreadLocalMap对象,这个对象是什么时候创建的呢? 在以上的几个步骤中我们没有发现创建该对象的过程..

我们回到标记1和标记2处,标记1获取到mLooper后,紧接着标记2处对mLooper做了非空判断,而此时程序抛了异常,说明mLooper是null,回到getMap(t)这里,好像并不能找出什么重要的线索。

换个角度想一想,异常信息提示我们应该要调用 Looper.prepare(),那我们先去Looper的prepare方法里找找线索。

public static void prepare() {
        prepare(true);
    }

    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {   //  标记3
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

我们看看这个带参数的prepare方法,标记3处判断sThreadLocal.get()是否不等于null,当我们第一次调用Looper.prepare()时,sThreadLocal.get()一定为null,为什么这么说呢? 因为该值不为空的话,那么标记1处所获取到的对象也不会为空,也就不会抛出异常!所以第一次进来肯定是null,第二次进来的话就不是null了,抛出了异常"Only one Looper may be created per thread",也说明了在子线程中只能调用Looper.prepare()一次。所以我们看看 sThreadLocal.set(new Looper(quitAllowed))做了哪些操作。

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

往set(T value)中传入了一个 Looper对象,set()方法里第二行还是调用了 getMap(t),由于是第一次进来返回map==null,我们看看 createMap(t, value) :

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

可以看到执行到这里的时候,才对当前线程的threadLocals进行了赋值,ThreadLocalMap以当前线程为 key,以Looper为值进行存储。

做一个总结,回到Looper.myLooper()这里:

/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
    
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

当我们没有调用Looper.prepare()时,当前thread的threadLocals还没有创建,getMap()返回为null,get()方法执行到了setInitialValue()这里

private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }
    
    protected T initialValue() {
        return null;
    }

可以明显的看到,setInitialValue()返回的值是固定的就是null。setInitialValue返回null,也就是get()返回null,接着myLooper()返回null,程序也就抛出了异常!

分析完源码,也不难做出结论,一个线程只能有一个looper对象,这个looper会以Map形式存储在储在当前线程的ThreadLocal中。

上一篇 下一篇

猜你喜欢

热点阅读