设计模式之单例模式
1.饿汉式-线程不安全
public class People{
private static People people=new People();
private People(){
}
public static People getInstance(){
return people;
}
}
2.懒汉式-线程不安全
public class People{
private static People people;
private People(){}
public static People getInstance(){
if(people==null){
people=new People();
}
return people;
}
}
3.加锁-不够灵活
public class People{
private static People people;
private People(){}
public synchronized static People getInstance(){
if(people==null){
people=new People();
}
return people;
}
}
4.加锁-灵活
public class People{
private static People people;
private People(){}
public synchronized static People getInstance(){
synchronized(People.class){
if(people==null){
people=new People();
}
}
return people;
}
}
5.双端检索
加锁之后如果两个线程抢锁,导致一个线程创建了对象另一个线程在等待,等待结束后也创建了对象这种情况可以使用双端检索
public class People{
private volatile static People people;
private People(){
}
public static People getInstance(){
if(people==null){
synchronized(People.class){
if(people==null){
people=new People();
}
}
}
return people;
}
}
6.静态内部类
public class People{
private People(){}
static class inner{
private final static People people=new People();
}
public static People getInstance(){
return inner.people;
}
}
请使用5,6