在单例模式中分为懒汉式和饿汉式,其中饿汉式是线程安全的,要实现懒汉式线程安全要做双重的判断,其中代码如下:
public static class Singleton(){
private volatile static Singleton instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null) {
synchronized (Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
分析:当A线程判断instance为null时,CPU的资源被B抢占,然后执行同步方法,获得instance实例,这时A获得CPU资源,因为B已经将共享资源的实例化了,所以再次判断时是不为null的,因此是线程安全的。为了防止指令重排,使用volatile对对象进行修饰,以保证其原子的可见性,从而阻止指令重排。
2395

被折叠的 条评论
为什么被折叠?



