[英]Is a static final char[] thread safe?
So if I have 所以,如果我有
private static final char[] SOME_CHARS;
Is that thread safe? 这个线程安全吗? By that I mean if I have multiple threads referring to the chars in that array (but not changing them), will anything go wrong?
我的意思是,如果我有多个线程引用该数组中的字符(但不更改它们),那么会出现什么问题吗?
eg 例如
private class someThread extends Thread(){
public void run(){
for(int i = 0; i < someIndexInSomeChars;i++){
System.out.println(SOME_CHARS[i]);
}
}
In other words do I need to put the char[] into some sort of Java collection with thread support? 换句话说,我需要将char []放入某种带有线程支持的Java集合中吗?
If you don't change them after initialization, it should be fine. 如果你在初始化后没有更改它们,它应该没问题。 (Note that this relies on it being a
static final
variable - the way that classes are initialized will ensure that all threads see the initialized array reference correctly.) (请注意,这依赖于它是一个
static final
变量 - 初始化类的方式将确保所有线程正确地看到初始化的数组引用。)
Arrays are safe to read from multiple threads. 从多个线程读取数组是安全的。 You could even write from multiple threads if you didn't mind seeing stale results - you wouldn't end up "corrupting" the collection itself.
如果您不介意看到陈旧的结果,您甚至可以从多个线程编写 - 您最终不会“破坏”集合本身。 (Unlike many other collections, you can't change the size of an array anyway... there's no state to modify other than the elements themselves.)
(与许多其他集合不同,您无论如何都无法更改数组的大小......除了元素本身之外,没有任何状态可以修改。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.