饿汉模式
优点:线程安全,不存在并发问题
缺点:在类加载之前就创建好了对象
public class Singleton {
private Singleton(){}
private static Singleton singleton = new Singleton();
public static Singleton getInstance(){
return singleton;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(()->{
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
});
thread.start();
}
}
}
懒汉模式(不推荐使用)
缺点:线程不安全,存在并发问题
public class Singleton {
private Singleton(){};
private static Singleton singleton = null;
public static Singleton getInstance(){
if (singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
懒汉模式 DCL(double check lock)(推荐)
public class Singleton {
private Singleton(){};
private volatile static Singleton singleton = null;
public static Singleton getInstance(){
if (singleton == null){
synchronized (Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(()->{
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
});
thread.start();
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于