ThreadLocal解析

ThreadLocal解析
功能
线程间保存自己的变量副本,保证线程安全
方法间传递变量
源码解析
set方法讲变量存储到跟线程相关的map中
    public void set(T value) {        Thread t = Thread.currentThread();
        // 获取当前线程的map
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    ThreadLocalMap getMap(Thread t) {
		// 线程对象里面包含这个map
        return t.threadLocals;
    }
get方法
    public T get() {        Thread t = Thread.currentThread();
		// 取出对应map
        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();
    }
参考
- https://blog.csdn.net/coslay/article/details/38293689
 - https://www.liaoxuefeng.com/wiki/1252599548343744/1306581251653666
 
以上是 ThreadLocal解析 的全部内容, 来源链接: utcz.com/z/514958.html



