下面通过一个例子来证明通过ThreadLocal能达到在每个线程中创建变量副本的效果:
public class TestThreadLocal {
public static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String []args){
threadLocal.set("hello world");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread:"+threadLocal.get());
}
});
thread.start();
System.out.println("main:"+threadLocal.get());
}
}
控制台输出:
main:hello world
thread:null
ThreadLocal相关类图结构:
Thread类中有一个ThreadLocalMap类型的变量threadLocals。threadLocals用来存储实际的变量副本,key为当前ThreadLocal变量,value为变量副本。
初始化时,在Thread中threadLocals变量为null,只有当前线程第一次调用Thread的set()或get()方法thread中threadLocal进行初始化,并且以当前ThreadLocal变量为key,以ThreadLocal要保存的副本变量为value,存到threadLocals。如果要获取副本变量,通过ThreadLocal的get方法。
ThreadLocal最常见的使用场景是用来解决数据库连接、Session管理等。