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();
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容