1. 概述
ThreadLocal为每个使用该变量的线程提供独立的变量副本,因此每一个线程都可以独立地改变自己的副本,而不会影响其他线程。
入门例子:
public class ThreadLocalStudy {
static ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
new Thread(
() -> {
stringThreadLocal.set("5");
System.out.println(stringThreadLocal.get());
test();
}
).start();
TimeUnit.SECONDS.sleep(10);
}
public static void test() {
System.out.println(stringThreadLocal.get());
}
}
2. 源码阅读
ThreadLocal.ThreadLocalMap threadLocals 是 Thread局部属性字段
public class Thread implements Runnable {
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap