zoukankan      html  css  js  c++  java
  • ThreadLocal笔记

    1、ThreadLocal的作用是什么?

           ThreadLocal是一个泛型类,将保存在其中的值与当前的线程关联起来,这样每个线程看到的值对于其他线程来说都是不可见的,这个技术被称为线程封闭?(Java并发编程实战里面这么叫:))这样就保证了线程安全。

    2、怎么实现的呢?

         先提一下内部类的概念:

             A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass, a nested class can be declared privatepublicprotected, or package private. (Recall that outer classes can only be declared public or package private.)

          我们ThreadLocal内部就维护了一个Static nested classes(静态内部类):ThreadLocalMap,ThreadLocalMap中维护着我们放进去的值和当前ThreadLocal实例。

          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();
        }

          我们调用get()方法后,先获取当前线程(Thread.currentThread),在Thread类中声明了ThreadLocalMap类属性:threadLocals

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

         而ThreadLocalMap中又存放了我们放进去的值,这样就保证了每个线程工作时,操作的是与我们线程相关的值(ThreadLocalMap),确保了线程之间的安全性。

     3、写在最后

         ThreadLocalMap如何维护我们放进去的值?自己翻翻源码看看就明白了

  • 相关阅读:
    559. N叉树的最大深度
    999. 车的可用捕获量
    1051. 高度检查器
    238. 除自身以外数组的乘积
    【Go】Go语言的%d,%p,%v等占位符的使用
    【Java】commons-lang3中DateUtils类方法介绍
    【Java】时间戳与Date相互转换
    【Linux】crontab定时任务用用法
    【Java】使用Lambda排序集合
    【PBFT】拜占庭容错
  • 原文地址:https://www.cnblogs.com/Non-Tecnology/p/6535229.html
Copyright © 2011-2022 走看看