熟悉Looper源碼的朋友可能知道,looper與線程綁定並不是直接set進去的,而是通過ThreadLocal這個東西間接將looper的引用交給當前線程持有的。
Looper.java
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));
}
ThreadLocal,java
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
可以看出,每個線程中維護了一個ThreadLocalMap,這個map就是這個線程用於存儲外界資源對象的。而添加的過程是通過ThreadLocal這樣一箇中介來完成的,同時這個ThreadLocal就是作爲key存儲到ThreadLocalMap中的。
這樣做的好處是,每個線程中都維護了一個map,那麼雖然是對應同一個ThreadLocal,但取到的卻是不同的值,解決了線程共用資源的問題。
所以ThreadLocal是解決共享資源的另一個思路,“拿空間換時間”;而sysnchrozied卻是“那時間換空間”.