ThreadLocal

1.直接上测试代码

public class ThreadlocalTest extends Thread{
    public static ThreadLocal threadLocal=new ThreadLocal();
    private String name;
    public ThreadlocalTest(String name){
        this.name=name;
    }
    @Override
    public void run() {
        threadLocal.set(currentThread().getName()+"+++++++"+name);
        System.out.println(threadLocal.get());
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new ThreadlocalTest("thread"+i).start();
        }
    }
}

运行结果:

每个线程都只是get自己的值。

上源码 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(t),他就是Thread这个类的一个成员变量,在第一次set的时候进行初始化

 ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }


  /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

继续看createMap(t,value)

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
  

ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            //这里key就是当前threadLocal对象,value是要保存的值
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

ThreadLocalMap是ThreadLocal的衣蛾内部类,可以理解为是一个hashmap

get()方法

   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就是给每一个线程创建一个ThreadLocalMap,用于保证各自线程get的值都是自己set的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值