ThreadLocal原理讲解

2020-08-28  本文已影响0人  码而优则仕

ThreadLocal的基本原理是每个线程都有两个属性 ,
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
属性的类型是 ThreadLocal 的内部类,两者的区别是后者可继承,即子线程继承父线程的该属性值。
继承的实现是在线程的构造函数中实现的,读取当前线程的父级线程该属性,创建当前线程的该属性 inheritableThreadLocals

public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }

 private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        //这里完成继承的逻辑
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

这两个属性是线程自带的属性,ThreadLocal其实就是一个工具,当当前线程通过ThreadLocal 设置某个值的时候,其实就是利用了当前线程自带的这个属性 Map 将 调用的当前ThreadLocal对象 引用作为 key,要设置的值作为 value设置到当前线程的 Map中去

     public void set(T value) {
       //获取当前线程
        Thread t = Thread.currentThread();
        //取出当前线程的 Map
        ThreadLocalMap map = getMap(t);
        if (map != null)
             //以 ThreadLocal 对象引用为key 设置到线程的 Map
            map.set(this, value);
        else
            createMap(t, value);
    }

当当前线程通过ThreadLocal获取值的时候,也是先查当前线程的Map,然后获取调用 get方法的 ThreadLocal 对象应用为key 对应的value

    public T get() {
         //获取当前线程
        Thread t = Thread.currentThread();
        //获取当前线程的 map属性
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            //从map 中获取以调用当前get 方法的 ThreadLocal 的引用为key 的value
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

移除就是直接获取当前线程中的 Map,将当前调用remove方法的 ThreadLocal引用对于作为 key ,从map中移除

 public void remove() {
          //获取当前线程中的 Map
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }
上一篇 下一篇

猜你喜欢

热点阅读