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如何维护我们放进去的值?自己翻翻源码看看就明白了

  • 相关阅读:
    Python3 使用requests库读取本地保存的cookie文件实现免登录访问
    Python3 使用requests库登陆知乎并保存cookie为本地文件
    python中的ConfigParser模块
    python中json的使用
    python中的IO模块
    python中的apscheduler模块
    ubuntu14静态ip配置
    在ubuntu14中搭建邮箱服务器
    python 生成器
    python中列表生成式
  • 原文地址:https://www.cnblogs.com/Non-Tecnology/p/6535229.html
Copyright © 2011-2022 走看看