Handler笔记

Handler学习笔记

1.为什么一个线程只有一个Looper、只有一个MessageQueue?

答:对于一个类我们需要共享变量值的时候我们会采用public static的形式,对于线程来说如果一个线程需要有自己的共享变量,此时就会使用ThreadLocal类来实现,首先Looper中使用了static final ThreadLocal ,使得每个线程都有对应的looper,如此一来可使每一个线程只有一个Looper,其次就是Looper的构造函数为私有,外界需要通过无参的prepare()方法才能构建Looper,此时无参的prepare会调用有参的的方法传入true。

代码如下:

    /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    public static void prepare() {
           prepare(true);
    }
    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

有参数的prepare方法会校验当前线程是否已经构建了Looper,是则抛出异常,由此可见对于每个线程来说只能有一个Looper,由源码追踪可以得出,MessageQueue是在构建Looper的时候构建的,然:Looper相对于线程惟一,则MessageQueue也对于线程惟一,不是同理可得,因为通过下面代码可以看出,handler发消息,其内部都是通过Looper的MessageQueue去轮询的,源码如下:

    我们一般构建Handler的时候都会new一个Hanler,调用的是其无参的构造
    函数,我们看到其无参构造函数中又调用了带两个参数的构造函数,我们
    找到它
    /**
     * 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);
    }
    
    
    
     /*
     * Set this flag to true to detect anonymous, local or member classes
     * that extend this Handler class and that are not static. These kind
     * of classes can potentially create leaks.
     */
    private static final boolean FIND_POTENTIAL_LEAKS = false;
    
    public Handler(Callback callback, boolean async) {
        //改参数是上面这个false的,还是final的static的,应该是写代码的
        //debug的吧,具体干啥不清楚。略过这个if往下看
        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());
            }
        }
        //到了这步,我们可以看到Handler调用了Looper.myLooper();
        //其实就是调用Looper中的sThreadLocal.get();如果当前线程
        //未构建Looper则放回null,此时会抛出异常,如果不为null,
        //则获取自己的mQueue赋值给Handler的mQueue。其实都是用的
        //Looper的MessageQueue
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

由此可见一个线程只有一个Looper、只有一个MessageQueue。


2.如何获取当前线程的Looper?是怎么实现的?(理解ThreadLocal)

答:问题1提到了ThreadLocal,该类结合Thread使用,会根据当前线程存入当前线程特有的参数,以实现线程本身与其他线程之间的数据隔离。而在Looper中对ThreadLocal本身设定了泛型,也就是规定了存入的数据为Looper类型,当我们通过prepare
方法构建Looper后,同时还会为当前线程设置该looper,然后通过Looper.myLopper
可以获得当前线程的looper对象。
源码如下:

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


3.是不是任何线程都可以实例化Handler?有没有什么约束条件?

答:是的,但是有约束条件,那就是如果实例化Handler的线程不是主线程,则需要
使用者为该线程创建一个Looper对象否则会报异常。


未完待续…

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值