定义一个ThreadLocal工具类。
package com.java;
import java.util.HashMap;
import java.util.Map;
public class UtilsThreadContext {
private static final ThreadLocal<Map<Object, Object>> currentThreadCache = new ThreadLocal<>();
public static Map<Object, Object> get() {
return currentThreadCache.get();
}
public static <T> T get(Object fqn) {
Map<Object, Object> map = currentThreadCache.get();
if (map == null) {
return null;
}
return (T) map.get(fqn);
}
public static boolean containsKey(Object fqn) {
Map<Object, Object> map = currentThreadCache.get();
if (map == null) {
return false;
}
return map.containsKey(fqn);
}
public static void put(Object fqn, Object value) {
if (fqn != null) {
Map<Object, Object> map = currentThreadCache.get();
if (map == null) {
map = new HashMap<Object, Object>();
currentThreadCache.set(map);
}
map.put(fqn, value);
}
}
public static void putAll(Map<?, ?> m) {
if (m != null) {
Map<Object, Object> map = currentThreadCache.get();
if (map == null) {
map = new HashMap<Object, Object>();
currentThreadCache.set(map);
}
map.putAll(m);
}
}
public static void delete(Object fqn) {
if (fqn != null) {
Map<Object, Object> map = currentThreadCache.get();
if (map != null) {
map.remove(fqn);
}
}
}
public static void cleanup() {
try {
currentThreadCache.remove();
} catch (Throwable e) {
}
}
}
测试:
public class test {
public static void main(String[] args) {
IntStream.range(0, 10).forEach(i -> {
new Thread(() -> {
String msg = "消息"+i;
UtilsThreadContext.put(i, msg);
System.out.println(Thread.currentThread().getName() + ":" + "放入消息是"+msg);
System.out.println(Thread.currentThread().getName() + ":" + "取出消息是"+UtilsThreadContext.get(i));
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
测试结果:
每个线程获取的变量都是当前线程的。互不影响。

本文介绍了一个实用的ThreadLocal工具类实现,该工具类能够帮助开发者更好地管理线程局部变量,确保不同线程间的变量隔离。文章通过示例展示了如何使用这个工具类来存储和检索线程局部变量。
840

被折叠的 条评论
为什么被折叠?



