求职面试的时候被问到了Java单例,于是文面试官是不是线程安全的,得到肯定后,写了一个双重锁的单例。总结了四种单例
/**
* 饿汉式单例模式
* @author zhouzhihu
*
*/
public class Singleton {
private static final Singleton INSTANCE=new Singleton();
private Singleton(){}
public Singleton getInstance(){
return INSTANCE;
}
}
/**
* 懒汉式单例
* @author zhouzhihu
*
*/
public class Singleton2 {
private Singleton2(){}
private static class SingletonHolder{
private final static Singleton2 INSTANCE=new Singleton2();
}
public Singleton2 getInstance(){
return SingletonHolder.INSTANCE;
}
}
--------------------------------------------------------------------------------------------------------------------------------------/**
* 普通加锁
* @author zhouzhihu
*
*/
public class Singleton3 {
private static Singleton3 instance=null;
private Singleton3(){}
public static synchronized Singleton3 getInstance(){
if(instance==null)
instance=new Singleton3();
return instance;
}
}
--------------------------------------------------------------------------------------------------------------------------------------/**
* 双重检测(加锁)
* @author zhouzhihu
*
*/
public class Singleton4 {
private static volatile Singleton4 instance=null;
private Singleton4(){}
public static Singleton4 getInstance(){
if(instance==null){
synchronized(Singleton4.class){
if(instance==null){
instance=new Singleton4();
}
}
}
return instance;
}
}