looper.mylooper 实质就是取当前线程的looper,这个Looper在prepare的时候创建并通过threadLocal存储起来的:
Looper中维护了一个final static的 sThreadLocal。
不清楚的ThreadLocal实质的我写了一篇自己的理解:对ThreadLocal的一点自己的理解
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));
}
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
getMainLooper是取主线程的looper
public static Looper getMainLooper() {
synchronized (Looper.class) {
return sMainLooper;
}
}
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
从上面可以看出来getMainLooper取得是sMainLooper,sMainLooper是static的。而sMainLooper是在prepareMainLooper中调用 sMainLooper = myLooper();本质获取当前线程的looper又因为prepareMainLooper是在主线程ActivityThread中调用的所以是主线程通过静态变量sMainLooper保存的.
面试问:主线程的looper能不能退出 ,handlerThread的线程能不能退出
其实看这个方法的 quitAllowed参数,主线程这个参数是false调用的是prepare(false),handlerThread调用的是prepare():
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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
MessageQueue(boolean quitAllowed) {
mQuitAllowed = quitAllowed;
mPtr = nativeInit();
}