码迷,mamicode.com
首页 > 其他好文 > 详细

ThreadLocal<T>学习总结

时间:2019-04-12 16:23:50      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:oid   ret   author   nbsp   div   note   current   entry   print   

public class ThreadLocalTest {

    /**
     * @param
     * @Author: xdj
     * @Date: 2019/4/12 10:16
     * @Description:
     * @return: void
     * ThreadLocal是一种变量类型,我们称之为“线程局部变量”
     * 每个线程访问这种变量的时候都会创建该变量的副本,这个变量副本为线程私有
     * ThreadLocal类型的变量一般用private static加以修饰
     */
    @Test
    public void test() {

         ThreadLocal threadLocal = new ThreadLocal(){
             @Override
             protected Object initialValue() {
                 return Thread.currentThread().getId();
             }
         };


//        threadLocal.set("测试threadLocal");

        System.out.println(threadLocal.get());

    }
}

学习ThreadLocal<T>,首先先从它的数据结构开始,ThreadLocal的内部类ThreadLocalMap

  
// 只是截取部分
static class ThreadLocalMap { /** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */ static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }

 

而ThreadLocalMap又存储在Thread中。

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

 

ThreadLocal中的几个重要方法,提供了重要的操作

                                                                               技术图片

get方法

                                                                            技术图片

这里通过getMap方法获取当前线程中的所有ThreadLocal<T>记录threadLocals,先判断是否已有值,如果没有则调用setInitialvalue()赋值

                                                                       技术图片

set()方法

                  技术图片

先判断是否有值了,如果有则覆盖,没有则创建新的Map对象。

remove方法

                  技术图片

总结:Thread通过ThreadLocalMap来存储线程中的变量,第一次获取时需要先通过set()将值保存进map中。通过泛型来区分给个变量的key。

参考:

  https://www.cnblogs.com/dolphin0520/p/3920407.html

 

ThreadLocal<T>学习总结

标签:oid   ret   author   nbsp   div   note   current   entry   print   

原文地址:https://www.cnblogs.com/angleshoot/p/10696686.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!