一句话解释ThreadLocal类

时间:2022-07-25
本文章向大家介绍一句话解释ThreadLocal类,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一个Thread类,有一个treadlocals变量,类型为ThreadLocal.ThreadLocalMap 初始值为null,这个变量,属于该线程,这个map由ThreadLocal类维护。

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

一旦,由 new ThreadLocal() 操作,,并set值,那么创建ThreadLocalMap。

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

其中key等于,ThreadLocal对象,value=值。

     ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

如果此线程再new一个ThreadLocal() ,再调用set方法,那么这个threadlocals变量会有两个值。 key为新建的ThreadLocal对象。 其实,一个线程,有一个共享变量,供多个threadlocals使用。

测试案例如下:

 ThreadLocal l1 = new ThreadLocal();
        ThreadLocal l2 = new ThreadLocal();
        l1.set("1");
        l2.set("2");
        System.out.println(l2.get());

附上实例:

public class ThreadLocalTest {
    int p = 1;

    public int getP() {
        return p;
    }

    public void setP(int p) {
        this.p = p;
    }

    public static void main(String[] args)  {

        ThreadLocalTest s1 = new ThreadLocalTest();
        System.out.println(s1);
        System.out.println("s1 p="+s1.getP());

        ThreadLocal<ThreadLocalTest> main = new ThreadLocal(){
            @Override
            protected Object initialValue() {
                return s1;
            }
        };
        ThreadLocalTest m =  main.get();
        m.setP(111);
        System.out.println(m);
        System.out.println("main线程 p="+m.getP());
        new Thread(()->{
            ThreadLocal<ThreadLocalTest> t = new ThreadLocal(){
                @Override
                protected Object initialValue() {
                    return s1;
                }
            };
            ThreadLocalTest t2 = t.get();
            t2.setP(222);
            System.out.println("子线程 p="+t2.getP());
            System.out.println(t2);
        }).start();
    }
}