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

  • 相关阅读:
    UITableView移除某行的分割线和让分割线宽度为cell的宽度
    UIButton防止被重复点击
    给View添加手势,防止点击View上其他视图触发点击效果
    自定义导航栏返回时的滑动手势处理
    一个UITableViewCell的简单动画效果
    二维码扫描
    代理的使用
    常用网站
    IOS 自定义View X系列出现一条线条
    UILabel自适应文本,让文本自适应
  • 原文地址:https://www.cnblogs.com/Non-Tecnology/p/6535229.html
Copyright © 2011-2022 走看看