美文网首页
Java之ThreadLocal是个什么玩意儿。

Java之ThreadLocal是个什么玩意儿。

作者: 大雨滂沱在关外 | 来源:发表于2020-11-11 21:21 被阅读0次
    • 首先低调地写上一段代码
    /*
     * @author zhangxiaomin
     * @email 1396729865@qq.com
     */
    public class HelloWorld{
        static ThreadLocal<String> threadLocal = new ThreadLocal<>(){{
            this.set("main");
        }};
        public static void main(String[] args) {
            System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
            Thread zhangxiaomin,zhangsan;
            (zhangxiaomin = new Thread(()->{
                System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
                threadLocal.set("zhangxiaomin");
                System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
            },"zhangxiaomin")).start();
            (zhangsan = new Thread(()->{
                System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
                threadLocal.set("zhangsan");
                System.out.printf("the threadlocal of %s 's value is %s\n'",Thread.currentThread().getName(),threadLocal.get());
            },"zhangsan")).start();
        }
    }
    
    • 接着执行一下。
    • 问题来了?为毛线zhangxiaoomin和zhangsan这个线程首先打印出来的是一个null呢? 这个ThreadLocal不应该是一个共享变量吗?这三个线程不应该都保持一致嘛?
    • 下一步看一下ThreadLocal的源码(请注意看我的注释)
    
        /**
         * Get the map associated with a ThreadLocal. Overridden in
         * InheritableThreadLocal.
         *  第一步先看这个方法。返回了一个线程的内部对象。而且看下边的调用,传递的都是Thread.CurrentThread().
         * @param  t the current thread
         * @return the map
         */
        ThreadLocalMap getMap(Thread t) {
            return t.threadLocals;
        }
    
        /**
         * Sets the current thread's copy of this thread-local variable
         * to the specified value.  Most subclasses will have no need to
         * override this method, relying solely on the {@link #initialValue}
         * method to set the values of thread-locals.
        * 第二步:ThreadLocal调用set方法的时候。创建了一个新的对象并且赋值
         * @param value the value to be stored in the current thread's copy of
         *        this thread-local.
         */
        public void set(T value) {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null) {
                map.set(this, value);
            } else {
                createMap(t, value);
            }
        }
        /**
         * Create the map associated with a ThreadLocal. Overridden in
         * InheritableThreadLocal.
         *
         * @param t the current thread
         * @param firstValue value for the initial entry of the map
         */
        void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }
    
        /**
         * Returns the value in the current thread's copy of this
         * thread-local variable.  If the variable has no value for the
         * current thread, it is first initialized to the value returned
         * by an invocation of the {@link #initialValue} method.
         * 下边的代码是考虑到是用initialValue()初始化ThreadLocal的数据。明显使用了延迟加载的方式。
         * @return the current thread's value of this thread-local
         */
        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();
        }
    
        /**
         * Variant of set() to establish initialValue. Used instead
         * of set() in case user has overridden the set() method.
         *
         * @return the initial value
         */
        private T setInitialValue() {
            T value = initialValue();
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null) {
                map.set(this, value);
            } else {
                createMap(t, value);
            }
            if (this instanceof TerminatingThreadLocal) {
                TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
            }
            return value;
        }
    
    • 总结:使用ThreadLocal变量本质上操作的是当前线程的内部变量ThreadLocalMap
    
            /**
             * Construct a new map initially containing (firstKey, firstValue).
             * ThreadLocalMaps are constructed lazily, so we only create
             * one when we have at least one entry to put in it.
             */
            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);
            }
            /**
             * Construct a new map including all Inheritable ThreadLocals
             * from given parent map. Called only by createInheritedMap.
             *
             * @param parentMap the map associated with parent thread.
             */
            private ThreadLocalMap(ThreadLocalMap parentMap) {
                Entry[] parentTable = parentMap.table;
                int len = parentTable.length;
                setThreshold(len);
                table = new Entry[len];
                for (Entry e : parentTable) {
                    if (e != null) {
                        @SuppressWarnings("unchecked")
                        ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                        if (key != null) {
                            Object value = key.childValue(e.value);
                            Entry c = new Entry(key, value);
                            int h = key.threadLocalHashCode & (len - 1);
                            while (table[h] != null)
                                h = nextIndex(h, len);
                            table[h] = c;
                            size++;
                        }
                    }
                }
            }
    
    • 接下来的问题就本质了:知道这个东西有什么用呢??

    相关文章

      网友评论

          本文标题:Java之ThreadLocal是个什么玩意儿。

          本文链接:https://www.haomeiwen.com/subject/lcqlvktx.html