hello啊,各位观众姥爷们!!!本baby今天来报道了!哈哈哈哈哈嗝
ThreadLocal 是 Java 中用于实现线程本地变量的工具类,主要解决多线程环境下共享变量的线程安全问题。以下是其核心要点:
ThreadLocalMap:
Thread
类)内部维护一个 ThreadLocalMap
,以 ThreadLocal
实例为键,存储线程本地变量。关键操作:
ThreadLocalMap
。ThreadLocalMap
中获取值。ThreadLocalMap
中的值。原因:
ThreadLocalMap
的键(ThreadLocal
实例)是弱引用,值(变量副本)是强引用。ThreadLocal
实例被回收,但线程未终止,会导致值无法被回收(键为 null,但值仍存在)。解决方案:
remove()
清理条目。数据库连接管理:每个线程维护独立连接。
private static ThreadLocal<Connection> connectionHolder =
ThreadLocal.withInitial(() -> DriverManager.getConnection(DB_URL));
会话管理:保存用户请求上下文(如 Spring 的 RequestContextHolder
)。
日期格式化:避免 SimpleDateFormat
非线程安全。
private static ThreadLocal<SimpleDateFormat> dateFormat =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
remove()
。InheritableThreadLocal
。public class ThreadLocalDemo {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
// 任务 1:设置值为 100
executor.submit(() -> {
threadLocal.set(100);
try {
System.out.println("Thread 1: " + threadLocal.get()); // 输出 100
} finally {
threadLocal.remove(); // 清理
}
});
// 任务 2:未设置值,获取为 null
executor.submit(() -> {
System.out.println("Thread 2: " + threadLocal.get()); // 输出 null
});
executor.shutdown();
}
}
private static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
public static void main(String[] args) {
inheritableThreadLocal.set("Parent Value");
new Thread(() -> {
System.out.println(inheritableThreadLocal.get()); // 输出 "Parent Value"
}).start();
}