---------------------- android培训、java培训、期待与您交流! ----------------------
饿汉式:
public class Singleton{
private Singleton(){};
private static Singleton instance = new Singletion();
public static Singleton getInstance(){
return instance;
}
}
饿汉式提前实例化,没有懒汉式中多线程问题,但不管我们是不是调用getInstance()都会存在一个实例在内存中.
内部类式单例类:
public class Singleton{
private Singleton(){}
private class Singleton Holder(){
private static Singleton instance = new Singleton();
}
private static Singleton getInstance(){
return Singleton Holder.instance;
}
}
内部类式中,实现了延迟加载,只有我们调用了getInstance(),才会创建唯一的实例到内存中.并且也解决了懒汉式中多线程的问题.解决的方式是利用了Classloader的特性.
懒汉式:
public class Singleton{
private Singleton(){}
private static Singleton instance = null;
public static Singleton getInstance(){
if(instance==null){//--A --B
return instance = new Singleton();
}else{
return instance;
}
}
}
在懒汉式中,有线程A和B,当线程A运行到if()时,跳到线程B,当B也运行到8行时,两个线程的instance都为空,这样就会生成两个实例。解决的办法是同步:
public class Singleton{
private Singleton(){}
private static Singleton instance = null;
public static synchronized Singleton getInstance(){
if(instance==null){
return instance = new Singleton();
}else{
return instance;
}
}
}
懒汉式双检锁写法:
public class Singleton{
private static Singleton instance = null; //声明静态的单例对象的变量
private Singleton(){} //私有构造方法
public static Singleton getInstance(){ //外部通过此方法可以获取对象
if(instance == null){
synchronized(Singleton.class){ //保证了同一时间只能只能有一个对象访问此同步块
if(instance == null)
instance = new Singleton();
}
}
return instance; //返回创建好的对象
}
}