マルチスレッドケース-シングルトンモデル

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.レイジーマンモード-マルチスレッドバージョン-2番目の判断-高性能

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