gpt4 book ai didi

java - 单例规则不适用于静态成员变量

转载 作者:行者123 更新时间:2023-12-01 18:33:07 25 4
gpt4 key购买 nike

我正在使用单例设计模式。我使用一个静态变量作为我的类的成员变量。根据我的代码,即使我创建了单例类,它也会创建多个实例。请帮助我 这是正确的做事方式吗?//这是我的代码

public class MySingleton {
public static MySingleton instance = null;// new MySingleton();
static int count;

private MySingleton() {
count++;
}

public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
instance = new MySingleton();
}

}
return instance;
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

MySingleton news = new MySingleton().getInstance();
System.out.println(news.count);
MySingleton news1 = new MySingleton().getInstance();

System.out.println(news1.count);
MySingleton news2 = new MySingleton().getInstance();
System.out.println(news2.count);
}

}

最佳答案

您的代码不是线程安全的。

假设您从 2 个线程对 MySimgleton().getInstance() 进行了 2 次调用

如果上下文切换发生在 if - 之后,那么您将创建 2 个实例

关于java - 单例规则不适用于静态成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23246146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com