将ThreadLocal设置为静态变量,在set或get值得时候,会通过Thread.currentThread()拿到当前操作线程,在这个操作线程中设置|获取值,不会干扰到其它线程。
注意:ThreadLocal本身是存不了值得,存放数据是放在ThreadLocalMap(key为ThreadLocal)中的value
demo示例及运行结果
public class ThreadLocalDemo { private final static ThreadLocal<String> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { threadLocal.set("this is main Thread!"); System.out.println("主线程获取threadLocal中的值:" + threadLocal.get()); System.out.println(Thread.currentThread()); new Thread(() -> { System.out.println(Thread.currentThread()); System.out.println("赋值前,thread1线程获取threadLocal中的值:" + threadLocal.get()); threadLocal.set("this is thread1!"); System.out.println("赋值后,thread1线程获取threadLocal中的值:" + threadLocal.get()); }).start(); new Thread(() -> { System.out.println(Thread.currentThread()); System.out.println("赋值前,thread2线程获取threadLocal中的值:" + threadLocal.get()); threadLocal.set("this is thread2!"); System.out.println("赋值后,thread2线程获取threadLocal中的值:" + threadLocal.get()); }).start(); } }
运行结果
主线程获取threadLocal中的值:this is main Thread! Thread[main,5,main] Thread[Thread-0,5,main] 赋值前,thread1线程获取threadLocal中的值:null 赋值后,thread1线程获取threadLocal中的值:this is thread1! Thread[Thread-1,5,main] 赋值前,thread2线程获取threadLocal中的值:null 赋值后,thread2线程获取threadLocal中的值:this is thread2!
原文参考:
一个ThreadLocal和面试官大战30个回合 https://mp.weixin.qq.com/s/JUb2GR4CmokO0SklFeNmwg
思考:
当存在多个ThreadLocal 对象,在同一个线程中,其放入的信息都在该线程中的ThreadLocalMap中,以ThreadLocal为key,设计hash表的意图就是这个吧,相互取值不干扰