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

  • 相关阅读:
    hdu2083
    斐波那数
    hdu2000~hdu2099
    hdu2070
    hdu2071
    hdu2095
    TSINGSEE青犀视频云边端架构视频直播点播平台/人脸识别系统EasyDSS 如何开启debug 日志?
    RTMP协议视频直播点播智能分析平台EasyDSS如何增加Stream模块实现TCP代理?
    RTMP推流平台/视频直播点播分析平台/人脸识别系统EasyDSS如何实现RTMP负载均衡?
    关于视频智能分析平台人脸识别/车牌识别系统EasyDSS登录及直播点播的安全防盗链验证说明
  • 原文地址:https://www.cnblogs.com/Non-Tecnology/p/6535229.html
Copyright © 2011-2022 走看看