原文地址:https://my.oschina.net/yangchunlian/blog/1607947
第一种:饿汉模式(线程安全)
public class Single2 {
private static Single2 instance = new Single2();
private Single2(){
System.out.println("Single2: " + System.nanoTime());
}
public static Single2 getInstance(){
return instance;
}
}
第二种:懒汉模式 (如果方法没有synchronized,则线程不安全)
public class Single3 {
private static Single3 instance = null;
private Single3(){
System.out.println("Single3: " + System.nanoTime());
}
public static synchronized Single3 getInstance(){
if(instance == null){
instance = new Single3();
}
return instance;
}
}
第三种:懒汉模式改良版(线程安全,使用了double-check,即check-加锁-check,目的是为了减少同步的开销)
public class Single4 {
private volatile static Single4 instance = null;
private Single4(){
System.out.println("Single4: " + System.nanoTime());
}
public static Single4 getInstance(){
if(instance == null){
synchronized (Single4.class) {
if(instance == null){
instance = new Single4();
}
}
}
return instance;
}
}
第四种:利用私有的内部工厂类(线程安全,内部类也可以换成内部接口,不过工厂类变量的作用域要改为public了。)
public class Singleton {
private Singleton(){
System.out.println("Singleton: " + System.nanoTime());
}
public static Singleton getInstance(){
return SingletonFactory.singletonInstance;
}
private static class SingletonFactory{
private static Singleton singletonInstance = new Singleton();
}
}