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

前言

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中。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容