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)。
每个线程中维护一个 ThreadLocalMap,ThreadLocalMap 虽然名字里有 Map,实际上是 Entry 数组。Entry 数组中 Entry 的 key 是 ThreadLocal,Value 是 保存的属性。下面以一段代码举例:
public static void main(String[] args) {
ThreadLocal<Integer> tl = new ThreadLocal<>();
tl.set(1);
}
用法
Example1
import java.util.concurrent.TimeUnit;
public class ThreadLocal2 {
static ThreadLocal<Person> tl = new ThreadLocal<>();
public static void main(String[] args) {
new Thread(()->{
try {
//先睡两秒
TimeUnit