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

posted @ 2017-03-11 16:16  selrain  阅读(170)  评论(0编辑  收藏  举报