ThreadLocal为每个线程提供独立变量副本,避免并发冲突。通过set()和get()方法实现线程隔离,常用于用户上下文传递,如在请求处理中保存登录信息,并需在finally块中调用remove()防止内存泄漏;使用InheritableThreadLocal可让子线程继承父线程数据,但修改不影响已创建的子线程。
在多线程编程中,共享变量常常带来线程安全问题。为了在不加锁的前提下让每个线程拥有独立的数据副本,ThreadLocal 是一个非常实用的工具。它为每个线程提供独立的变量副本,避免了竞争条件,简化了并发控制。
ThreadLocal 可以看作是一个线程级别的“局部变量存储容器”。每个线程通过 get() 和 set() 方法访问自己独有的变量副本。
以下是一个简单的示例:
public class ThreadLocalExample {
private static ThreadLocal threadLocalValue = new ThreadLocal<>() {
@Override
protected Integer initialValue() {
return 0;
}
};
public static void main(String[] args) {
Runnable task = () -> {
int value = threadLocalValue.get();
value += Math.random() * 100;
threadLocalValue.set(value);
System.out.println(Thread.currentThread().getName() + ": " + threadLocalValue.get());
};
new Thread(task).start();
new Thread(task).start();
}}
上述代码中,每个线程获取的 threadLocalValue 是相互隔离的,互不影响。
在 Web 应用中,常需要在同一线程的不同方法间传递用户信息(如登录用户 ID)。使用 ThreadLocal 可以避免层层传参。
示例:保存用户登录信息
public class UserContext { private static ThreadLocal
userHolder = new ThreadLocal<>(); public static void setUser(String userId) { userHolder.set(userId); } public static String getUser() { return userHolder.get(); } public static void clear() { userHolder.remove(); }}
在请求开始时设置用户,结束时清理:
// 模拟请求处理
public void handleRequest(String userId) {
UserContext.setUser(userId);
try {
// 调用业务逻辑,内部可直接通过 UserContext.getUser() 获取
ServiceA.process();
ServiceB.logAccess();
} finally {
UserContext.clear(); // 非常关键!防止内存泄漏
}
}
虽然 ThreadLocal 很方便,但使用不当容易引发问题。
普通 ThreadLocal 不会将值传递给子线程。如果希望子线程继承父线程的变量,可以使用 InheritableThreadLocal。
private static InheritableThreadLocalinheritableTL = new InheritableThreadLocal<>(); public static void main(String[] args) { inheritableTL.set("main-thread-data"); new Thread(() -> { System.out.println("Child thread: " + inheritableTL.get()); // 可以读取到 }).start(); }
注意:仅在创建子线程时复制一次值,后续父线程修改不影响子线程。
基本上就这些。合理使用 ThreadLocal 能让代码更清晰、线程更安全,关键是记得用完清除。