单例模式线程安全问题

sgj191024 / 2023-08-23 / 原文

饿汉式:

package com.atjava.test;

public class Single {

    private static Single single;

    private Single(){

    }

    public static Single getSingle() {
        return single;
    }
}

  懒汉式:

package com.atjava.test;

public class SingleHungry {
private static SingleHungry singleHungry = null;

private SingleHungry(){

}

public static SingleHungry getSingleHungry() {
if(singleHungry == null){
synchronized (SingleHungry.class){
if(singleHungry == null){
singleHungry = new SingleHungry();
}
}
}
return singleHungry;
}
}
声明为静态的可以通过类直接调用,实例对象是private,构造方法是private,这样其他类不能直接创建实例对象必须通过getInstace方法