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对象否则会报异常。
未完待续…