Java中四种线程安全的单例模式实现方式

2020-12-30 17:59:01 浏览数 (1)

第一种:饿汉模式(线程安全)

代码语言:javascript复制
public class Single2 {

    private static Single2 instance = new Single2();
    
    private Single2(){
        System.out.println("Single2: "   System.nanoTime());
    }
    
    public static Single2 getInstance(){
        return instance;
    }
}

第二种:懒汉模式 (如果方法没有synchronized,则线程不安全)

代码语言:javascript复制
public class Single3 {

    private static Single3 instance = null;
    
    private Single3(){
        System.out.println("Single3: "   System.nanoTime());
    }
    
    public static synchronized Single3 getInstance(){
        if(instance == null){
            instance = new Single3();
        }
        return instance;
    }
}

第三种:懒汉模式改良版(线程安全,使用了double-check,即check-加锁-check,目的是为了减少同步的开销)

代码语言:javascript复制
public class Single4 {

    private volatile static Single4 instance = null;
    
    private Single4(){
        System.out.println("Single4: "   System.nanoTime());
    }
    
    public static Single4 getInstance(){
        if(instance == null){
            synchronized (Single4.class) {
                if(instance == null){
                    instance = new Single4();
                }
            }
        }
        return instance;
    }
}

第四种:利用私有的内部工厂类(线程安全,内部类也可以换成内部接口,不过工厂类变量的作用于要改为public了。)

代码语言:javascript复制
public class Singleton {
    
    private Singleton(){
        System.out.println("Singleton: "   System.nanoTime());
    }
    
    public static Singleton getInstance(){
        return SingletonFactory.singletonInstance;
    }
    
    private static class SingletonFactory{
        private static Singleton singletonInstance = new Singleton();
    }
}

转自:https://www.nowcoder.com/profile/6801164/myFollowings/detail/13699402

0 人点赞