ThreadLocal
约 294 字小于 1 分钟
2025-08-24
作用
线程隔离+隐式传参 每个线程中含有一个成员变量ThreadLocalMap,即存储ThreadLocal的Map
public class Thread implements Runnable {
//与此线程有关的ThreadLocal值。由ThreadLocal类维护
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
}设计意图很明了,即ThreadLocal是存储在每一个线程之中,多个线程访问同一个ThreadLocal不会形成竞争,这便是线程隔离 此外存储在线程中还有另一个优势,方便的值传递,无论栈的调用有多深,只要是同一个线程都能访问已存的值,这是隐式传递
举个例子
以Spring中对请求的处理为例 通过RequestContextHolder这一个静态工具类将请求与线程进行绑定
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attrs.getRequest();
// 在线程的任何地方获取当前线程的请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();同样是两个好处,其一:在线程的任何地方法都能获取到当前的请求对象;其二:Spring 会同时接收许多个请求并分配线程进行处理,使用ThreadLocal能够实现天然的线程隔离
