public class DLCSingleton {
private static volatile DLCSingleton mInstance =null; //volatile关键字是为了禁止编译器对 volatile关键字修饰的变量进行重排序,并保证volatile变量的读操作发生在写操作之后
private DLCSingleton(){
}
public static DLCSingleton getmInstance(){ if(mInstance == null){ //第一次检查 synchronized (DLCSingleton.class){ //同步代码块 if(mInstance == null){ //第二次检查 mInstance = new DLCSingleton(); } } } return mInstance; } } DCL双重检查锁仅在真正创建mInstance实例的时候加上了synchronized关键字。。。而且使用volatile关键字修饰,是为了禁止编译器对volatile变量重排序,并且保证volatile变量的读操作发生在写操作之后。 |
|