写出两种Singleton(单例模式)的实现代码,并说明其特点
(1)DCL双检查锁机制
//使用双检查锁机功能,成功地解决了“懒汉模式”遇到多线程的问题。DCL也是大多数多线程结合单例模式使用的解决方案。
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton(){
}
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized (Singleton.class) {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
(2)静态内部类方式
//只用通过显式调用getInstance()方法时,才会显式装载SingletonHandler类,从而实例化uniqueInstance(只用第一次使用这个单例的实例的时候才加载,同时不会有线程安全问题)。
public class Singleton {
private static class SingletonHandler {
private static final Singleton uniqueInstance = new Singleton();
}
private Singleton(){
}
public static Singleton getInstance() {
return SingletonHandler.uniqueInstance;
}
}