1. Thread stores the ThreadLocalMap type

2. ThreadLocal is stored in ThreaLocalMap in the form of WeakPrefernce

static class Entry extends WeakReference<ThreadLocal<? >> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<? > k, Object v) { super(k); value = v; }}Copy the code

3. Get method of ThreadLocal

  • GetMap (this) -> get Entry-> get the value of the Entry
  • If no data is retrieved, initialValue is called, and other types are initialized via override, for example
   private static final ThreadLocal<Choreographer> sSfThreadInstance =
            new ThreadLocal<Choreographer>() {
                @Override
                protected Choreographer initialValue() {
                    Looper looper = Looper.myLooper();
                    if (looper == null) {
                        throw new IllegalStateException("The current thread must have a looper!");
                    }
                    returnnew Choreographer(looper, VSYNC_SOURCE_SURFACE_FLINGER); }};Copy the code