Java 中熟悉而又陌生的 ThreadLocal
ThreadLocal 是什么? 要学习一个新东西至少要知道它是什么?这点应该是确定的。那么 ThreadLocal 到底是什么呢?其实Thread(线程)、Local(本地)这两个单词都不算太难,在平时也是屡见不鲜,ThreadLocal 很容易让人望文生义,想当然地认为是一个“本地线程”。其实 ThreadLocal 并不是一个 Thread,而是 Thread 的局部变量。那么它的作用到底是什么?先来看看JDK(13)文档的解释: 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).