单例模式之饿汉式
//饿汉式
public class Singleton1 {
private Singleton1() {
}
private static Singleton1 instance = new Singleton1();
public static Singleton1 getInstance(){
return instance;
}
}
单例模式之懒汉式
//懒汉式、支持多并发、效率低
public class Singleton3 {
private Singleton3() {
}
private static Singleton3 instance = null;
public synchronized static Singleton3 getInstance(){
if (instance == null){
instance = new Singleton3();
}
return instance;
}
}
单例模式之双锁式
//double checked locking、支持多并发、效率高、添加volatile关键字
public class Singleton4 {
private Singleton4() {
}
private volatile static Singleton4 instance = null;
public static Singleton4 getInstance(){
if (instance == null){//1
synchronized (Singleton4.class) {
if (instance == null)//2
instance = new Singleton4();
}
}
return instance;
}
}
版权属于:sunjianhua
本文链接:https://sunjianhua.cn/archives/spring-bean-create.html
转载时须注明出处及本声明,如果不小心侵犯了您的权益,请联系邮箱:NTA2MTkzNjQ1QHFxLmNvbQ==