Singleton Hungry Man Mode and Lazy Man Mode

The singleton mode includes the hungry man mode and the lazy 
   man mode. 
   The first step is to change the default construction method to private, that is, the instance cannot be created in other places. The 
   second step is to create an instance in advance and initialize it. 
   The third step is to provide a method to get this instance
public class Singleton {
    //构造方法私有化
    private Singleton(){}
    //创建一个实例进行初始化
    //static类方法,只能访问类成员,类变量
    private static Singleton instance = new Singleton();
    //其他类只能通过getInstance来获取这个实例
    public static Singleton getInstance(){
        //如果这儿不是static,这个方法就是实例方法或者对象方法,只能通过实例去调用
        return instance;
    }
}
  Lazy mode 
   1. First change the construction method to private 
   2. Create an instance without initialization 
   3. Provide a method to obtain this instance and initialize it. 
   When this method is called externally, this instance must be used. time to initialize
//构造函数私有化
    private Singleton2(){}
    //创建实例,不进行初始化
    private static Singleton2 instance = null;
    //对外提供一个方法,获取该实例,并进行初始化
    public static Singleton2 getInstance(){
        //instance = new Singleton2();//只在第一次调用的时候初始化
        if(instance == null){ //读操作
            instance = new Singleton2(); //写操作
        }
        return instance;
    }
If it is called by two threads at the same time 
 , then both threads must initialize it, so it is necessary to lock to 
 satisfy the singleton mode. The locked object must be unique, 
 that is, there is only one object in a program to ensure multiple When threads access, lock the same object. 
 Only the first thread needs to initialize the instance, and the following threads only need to directly obtain the previous instance.

//构造函数私有化
    private Singleton2(){}
    //创建实例,不进行初始化
    private static Singleton2 instance = null;
    //对外提供一个方法,获取该实例,并进行初始化
    public static Singleton2 getInstance() {
        //instance = new Singleton2();//只在第一次调用的时候初始化
        synchronized (Singleton2.class) { //类对象,一个程序只有一个
            if (instance == null) { //读操作
                instance = new Singleton2(); //写操作
            }
            return instance;
        }
    }
But as long as the thread calls getInstance, it will be locked, which is very inefficient, so when the code is modified to instance==null, it is locked
//构造函数私有化
    private Singleton2(){}
    //创建实例,不进行初始化
    private static volatile Singleton2 instance = null;//禁止指令重排序
    //对外提供一个方法,获取该实例,并进行初始化
    public static Singleton2 getInstance() {
        //instance = new Singleton2();//只在第一次调用的时候初始化
        if (instance == null) {  //判断是否加锁
            synchronized (Singleton2.class) { //类对象,一个程序只有一个
                if (instance == null) { //读操作
                    instance = new Singleton2(); //写操作
                }
            }
        }
        return instance;
    }
}

Guess you like

Origin blog.csdn.net/crazy_tan/article/details/128648908