作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在对我编写的一些代码进行一些更改,以尝试将其更改为多线程解决方案。我的主类中的一些元素最初是静态的,并且必须作为我所做更改的一部分进行更改。我想将它们存储在 HashMap
中,使用 Thread
的 Id 作为检索项目的键 - 这样我就可以存储对 的引用>Runnable
类,并使用 getters/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 = String.valueOf(Thread.currentThread().getId());
HashMap<String, Object> hash = tContext.get(id);
if( hash == null ) {
hash = new HashMap<>();
tContext.put(id, hash);
}
Object o = hash.get(key);
return o;
}
}
我的问题是:这样做安全吗,还是我应该尝试寻找另一种方法来做到这一点?我的示例似乎工作正常,但我不确定是否会因此而产生任何其他副作用。
编辑:用法示例:
Foo foo = ((Foo)ThreadContext.getObject(Foo.CLASS_IDENTIFIER));
foo.doStuff();
最佳答案
已经有一种方法可以使用 JDK 的 ThreadLocal
来做到这一点,它为每个(本地)线程存储不同的引用。
关于java - 将对象存储在静态类中的散列中是否安全,使用线程 ID 检索该特定线程的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116955/
我是一名优秀的程序员,十分优秀!