定义一个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();
}
});
}
}
测试结果:
每个线程获取的变量都是当前线程的。互不影响。