我正在对我编写的一些代码进行一些更改,以尝试将其更改为多线程解决方案.我的主类中的一些元素最初是静态的,并且必须作为我正在进行的更改的一部分进行更改.我有想法将它们存储在a中HashMap,使用Id Thread作为检索项的键 - 这样我就可以Runnable在哈希中存储对类的引用,并使用getter/setters访问给定线程的所需属性.我定义了以下代码来执行此操作:
import java.util.HashMap;
public class ThreadContext {
private static HashMap<String, HashMap<String, Object>> tContext;
static {
initThreadContext();
}
public static void initThreadContext() {
String id = String.valueOf(Thread.currentThread().getId());
tContext = new HashMap<>();
}
public static void setObject(String key, Object o) {
String id = String.valueOf(Thread.currentThread().getId());
HashMap<String, Object> hash = tContext.get(id);
if( hash == null ) {
hash = new HashMap<>();
tContext.put(id, hash);
}
hash.put(key, o);
}
public static Object getObject(String key) {
String id …Run Code Online (Sandbox Code Playgroud)