1.如何使用?
public class ThreadLocalExample {
private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
Runnable task = () -> {
threadLocal.set("Hello from thread " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String value = threadLocal.get();
System.out.println(value);
threadLocal.remove();
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
}
}
2.如何理解?
每个thread线程上有一个threadlocalmap变量,用来存储当前线程的threadlocal数据。
当调用threadlocal的set或get方法时,本质上是操作本线程的threadlocalmap。key用来存储当前threadlocal,value用来存储值。
实际上,threadlocal只是用来操作当前thread线程threadlocalmap的工具类而已,threadlocalmap并不是存储在threadlocal中。
3.注意哪些问题?
1.内存泄露/溢出:需要手动调用threadlocal.remove()来销毁
4.应用场景有哪些?
1.多个场景需要用到同一种变量,但每个场景里所用到的变量值不同,需要相互隔离的。
2.隔离线程,存储一些不安全的工具对象。
3.spring中的事物。
4.springMVC中的httpsession,httpservletrequest,httpservletresponse