如何在Java中初始化ThreadLocal对象 [英] How to initialize ThreadLocal objects in Java
本文介绍了如何在Java中初始化ThreadLocal对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一个问题,我正在创建一个ThreadLocal并使用新的ThreadLocal初始化它。问题是,我在概念上只想要一个持久的列表,这个列表会延续线程的生命,但我不知道是否有办法在Java中初始化每个线程的东西。
I'm having an issue where I'm creating a ThreadLocal and initializing it with new ThreadLocal . The problem is, I really conceptually just want a persistent list that lasts the life of the thread, but I don't know if there's a way to initialize something per-thread in Java.
例如我想要的是:
ThreadLocal static {
myThreadLocalVariable.set(new ArrayList<Whatever>());
}
因此它为每个线程初始化它。我知道我可以这样做:
So that it initializes it for every thread. I know I can do this:
private static Whatever getMyVariable() {
Whatever w = myThreadLocalVariable.get();
if(w == null) {
w = new ArrayList<Whatever>();
myThreadLocalVariable.set(w);
}
return w;
}
但我真的不想每次都检查一下它被使用了。我能在这里做得更好吗?
but I'd really rather not have to do a check on that every time it's used. Is there anything better I can do here?
推荐答案
你只需覆盖 initialValue()
方法:
private static ThreadLocal<List<String>> myThreadLocal =
new ThreadLocal<List<String>>() {
@Override public List<String> initialValue() {
return new ArrayList<String>();
}
};
这篇关于如何在Java中初始化ThreadLocal对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文