饿汉模式:
class Single{
private staitc final Single s= new Single();
private Single(){}
public static Single getSingle(){
return s;
}
}
懒汉模式:
class Single{
private static Single s= null;
private Single(){}
public static Single getSingle(){
if(s == null){
-->A线程
-->B线程
s = new Single();
return s;
}
}
}
在这里使用懒汉模式有一个安全性问题:
就是s为共享数据,可能会并发的访问getSingle()方法。当多线程访问时,一个A线程进来后,可能调用了sleep()方法在这里沉睡;一个B线程也可能在沉睡,当A线程醒来后,就会new一个对象,B线程醒来也会new一个对象;这样就不符合我们单例模式的特点了。
解决方案:使用synchronized方法进行线程同步
另一个问题,当加了synchronized后,那么很多线程来访问时,都要判断一下锁是哪个,这就造成速率下降
解决方案:在synchronized方法后添加instance是否为null的判断,这样当下一个线程访问时发现instance非空后直接返回前面线程实例化后的对象
public staitc Single getSingle(){
if(s == null){
synchronized(Single.class){ -->B线程,等着A解锁才让进去
if(s == null){
-->A线程
s = new Single();
}
}
return s;
}
}