1.懒汉式,线程不安全
public class Singleton{
private Singleton() {}
private static Singleton instance;
public static Singleton getInstance(){
if (null == instance){
instance = new Singleton();
}
return instance;
}
}
2.懒汉式,线程安全
public class Singleton{
private Singleton() {}
private static Singleton instance;
public static synchronized Singleton getInstance(){
if (null == instance){
instance = new Singleton();
}
return instance;
}
}
3.饿汉式,线程安全
public class Singleton{
private Singleton() {}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
4.枚举,线程安全
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
5.双检锁/双重校验锁
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (null == singleton) {
synchronized (Singleton.class) {
if (null == singleton) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
网友评论