Java 对单身汉不太确定

Java 对单身汉不太确定,java,singleton,Java,Singleton,如果我有一个单件类,比如: public class MySingleton(){ private static MySingleton istance; private int element; private MySingleton(){element = 10;} public static MySingleton getIstance() { if(istance == null) istance =

如果我有一个单件类,比如:

public class MySingleton(){
    private static MySingleton istance;
    private int element;

    private MySingleton(){element = 10;}     

    public static MySingleton getIstance() {
        if(istance == null)
            istance = new Mysingleton();
        return istance;
    }
    public void setElement(int i ){
        element = i;
    }
    public int getElement(){
        return element;
    }
}
我想通过调用

MySingleton.getIstance().setElement(20)
它会改变距离的元素值吗?下面是一个例子:

... main () {
    MySingleton.getIstance().setElement(20);
    System.out.prinln(MySingleton.getIstance().getElement());
    // It displays 10, why ?

我不确定你的代码是否真的有效,azurefrog如何说,让你的代码同步,在你的行中
public static getIstance(){
你需要设置返回类型。

我建议你使用
enum
,因为它更简单,线程安全(但不是你的getter/setter)


我不确定上面的代码块是被复制进来的还是被重新键入的,但是我看到了一些基本的编译问题——当你在getInstance中设置MySingleton时,你需要检查大小写。另外,你的类声明不应该有(括号)。在修复这两个问题并运行basic main之后,我得到了20个

这与您所做的相同-没有同步或其他任何事情,但在单个线程上似乎没有必要

public class MySingleton{
    private static MySingleton istance;
    private int element;

    private MySingleton(){element = 10;}     

    public static MySingleton getIstance() {
        if(istance == null)
            istance = new MySingleton();
        return istance;
    }
    public void setElement(int i ){
        element = i;
    }
    public int getElement(){
        return element;
    }

    public static void main(String[] args) {
        System.out.println(MySingleton.getIstance().getElement());
        MySingleton.getIstance().setElement(20);
        System.out.println(MySingleton.getIstance().getElement());
    }

}
输出应为

10
20

你需要使你的get方法同步。另外,你的
getIstance()
方法没有返回类型。这是如何编译的呢?最后,当我运行你的代码(修改为编译)时,我得到了
20
,正如预期的那样。public static getIstance()是错误的,应该是public static MySingleton getIstance()显示的代码给出了预期的结果。可能您正在查看类的旧编译单元的执行情况。请更正所有键入错误好吗?(Mysingleton,prinln)@azurefrog
synchronized
在这种情况下与此无关。
synchronized
在这种情况下与此无关。这不是多线程环境,OP只使用主线程。为什么只在主线程上使用单线程?他可能只使用“一个线程”为了简化这个问题的例子,最好是在他的单音中添加synchronized,这是我们不知道的。如果这是一个特定的情况,应该通过代码操作帖子来证明。否则,问题将无法重现,因此问题应该被标记/关闭。或者一个静态的内部类:)@TheLostMind it's一种更复杂的方法来实现同样的事情;)我对静态初始值设定项的热爱使我达到了这一点。。是的,你是对的。枚举方法的开销相对较少:)@TheLostMind
Enum
也有一个静态初始值设定项。
interface
s;)@PeterLawrey-Wow.。速度很快。。非常感谢:)
10
20