多线程案列 — 单例模型

1.饿汉模式

/**
 * 单列模型 —— 饿汉模式
 */
public class Singleton {
    
    
    //只有这么一个对象
    private static Singleton instance = new Singleton();

    private Singleton(){
    
    

    }
    public static Singleton getInstance(){
    
    
        return instance;
    }
}

2.懒汉模式

1.懒汉模式-单线程版

/**
 * 单列模型 —— 饿汉模式
 * 基本思想就是,什么时候用到,什么时候在初始化对象,
 * 和饿汉模式共同点,只会有一个对象
 */

public class Singleton1 {
    
    
    private static Singleton1 instance = null;

    public static Singleton1 getInstance(){
    
    
        //有人要用到该对象了
        if (instance == null){
    
    
            instance = new Singleton1();
        }
        return instance;
    }
}

2.懒汉模式-多线程版-性能低

ublic class Singleton1 {
    
    
    private static Singleton1 instance = null;

    public synchronized static Singleton1 getInstance(){
    
    
        //有人要用到该对象了
        if (instance == null){
    
    
            instance = new Singleton1();
        }
        return instance;
    }
}

3.懒汉模式-多线程版-二次判断-性能高

public class Singleton1 {
    
    
//这里要加volatile保证执行的顺序性
    private static volatile Singleton1 instance = null;

    public static Singleton1 getInstance(){
    
    
        //有人要用到该对象了(多线程——二次判断——性能高——线程安全)
        if (instance == null){
    
    
            synchronized (Singleton1.class){
    
    
                if (instance == null){
    
    
                    instance = new Singleton1();
                }
            }
        }

        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45665172/article/details/113818056