美文网首页
ThreadLocal详解

ThreadLocal详解

作者: 轩逸君 | 来源:发表于2021-09-21 20:19 被阅读0次

    ThnreadLocal是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射,各个线程之间的变量互不干扰,在高并发场景下,可以实现无状态的调用,特别适用于各个线程依赖不通的变量值完成操作的场景。
    首先ThreadLocalMap 是Thread中的一个副本变量,ThreadLocalMap 为ThreadLocal中的静态类

    public class Thread implements Runnable {
        /* ThreadLocal values pertaining to this thread. This map is maintained
         * by the ThreabdLocal class. */
        ThreadLocal.ThreadLocalMap threadLocals = null;
        /*
         * InheritableThreadLocal values pertaining to this thread. This map is
         * maintained by the InheritableThreadLocal class.
         */
        ThreadLocal.Threa dLocalMap inheritableThreadLocals = null;
    }
    
    public class ThreadLocal<T> {
      static class ThreadLocalMap {
          static class Entry extends WeakReference<ThreadLocal<?>> {
                Object value;
                Entry(ThreadLocal<?> k, Object v) {
                    super(k);
                    value = v;
                }
            }
            private Entry[] table;
      }
    }
    

    t中保存一个弱引用Entry数组,Entry作为ThreadLocal的包装类,当ThreadLoca

    相关文章

      网友评论

          本文标题:ThreadLocal详解

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