java创建volatile类不能保证volatile类变量
假设以下单例:
public class Test{
private static volatile Test test = null;
private static int test_int = 0;
private static String test_string = "test";
public int getInt(){
return test_int;
}
public String getString(){
return test_string;
}
private static Test getInstance(){
if(test == null){
synchronized(Test.class){
if(test == null)
test = new Test();
}
}
}
通过将单例实例Test声明为volatile,Test_int和Test_string是否也被视为volatile,或者它们必须声明为volatile?我想,通过使类本身不稳定,那么该类下的所有内容也会不稳定。。。不过,我对此并不确定。提前谢谢
# 1 楼答案
不,它们不被认为是不稳定的只有变量
实话说,我个人会考虑使用^ {CD4>}和^ {CD5>}而不是^ {< CD6>}。我不知道其他人的情况,但我发现很难对易变的行为进行可靠的推理test
是易变的。在获得test
的价值后(通过getInstance
),其波动性与客户的其他行为无关请注意,您可能不希望
test_int
和test_string
变量是静态的