ThreadLocal

每一个线程都有一个ThreadLocalMap的存储结构,一个ThreadLocal变量都会被每个线程复制一份线程私有的变量,
通过Set(Object)对ThreadLocal变量赋值,通过get()获取值


public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map !=null)
map.set(this, value);
else
createMap(t, value);
}

public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map !=null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e !=null) {
@SuppressWarnings(“unchecked”)
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}

你可能感兴趣的:(ThreadLocal)