Familiar with the looper source of friends may know, looper and thread binding is not directly set in, but through threadlocal this thing indirectly to the looper of the reference to the current thread hold.
Looper.java
private static void Prepare (Boolean quitallowed) {
if (sthreadlocal.get () = null) {
throw new RuntimeException ("Only one Looper could 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;
}
As you can see, a threadlocalmap is maintained in each thread, and this map is used by this thread to store external resource objects. The added process is done by threadlocal such an intermediary, and the threadlocal is stored as a key in Threadlocalmap.
The advantage of this is that a map is maintained in each thread, so the same threadlocal is used, but different values are taken, which solves the problem of thread sharing resources.
So threadlocal is another way to solve shared resources, "take space for Time", while sysnchrozied is "change space".
Use of threadlocal