目录
2 Thread、ThreadLocal、ThreadLocalMap关系
1 ThreadLocal介绍
下面是ThreadLocal类里面的一句话:
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID)
翻译:此类提供线程局部变量。这些变量不同于它们的正常对应变量,因为每个访问一个(通过它的 get 或 set 方法)的线程都有它自己的、独立初始化的变量副本。 ThreadLocal 实例通常是希望将状态与线程相关联的类中的私有静态字段(例如,用户 ID 或事务 ID)
换句话说: ThreadLocal为每个线程创建了单独变量的副本,每个线程操作的都是属于自己的那一份数据,所以不用担心多线程共享数据的问题。
2 Thread、ThreadLocal、ThreadLocalMap关系
每个线程内部都有一个ThreadLocalMap的属性
而ThreadLocalMap是ThreadLocal的静态内部类:
ThreadLocalMap和我们平常使用的Map有所不同,ThreadLocalMap内部是由Entry类数组构成,Entry是key-value键值对,key就是ThreadLocal,value是我们要存储的值(后面具体),属于ThreadLocalMap的静态内部类。