首页 > 编程语言 > 详细

推荐使用的三种无线程安全问题的单例模式

时间:2018-12-03 16:11:51      阅读:185      评论:0      收藏:0      [点我收藏+]

1、饿汉式

public class Singleton        
{        
    private static Singleton instance = new Singleton();        
    private Singleton(){           
    }        
    public static Singleton getInstance(){        
             return instance;         
    }        
}

2、懒汉式的双重检查锁定

public class Singleton2 {
    
    private Singleton2() {}
    
    private static volatile Singleton2 instance;
    
    /**
     * 双重检查加锁
     * 
     * @return
     */
    public static Singleton2 getInstance () {
        // 自旋   while(true)
        if(instance == null) {//synchronized作为重量级锁,第一次实例化对象时候使用,读取的时候没必要进行代码锁定
            synchronized (Singleton2.class) {
                if(instance == null) {
                    instance = new Singleton2();  // 指令重排序
                    
                    // 申请一块内存空间   // 1
                    // 在这块空间里实例化对象  // 2
                    // instance的引用指向这块空间地址   // 3
                    //因此使用volatile防止指令重排序
                }
            }
        }
        return instance;
    }
}

3、内部类

public class Singleton{        
    private Singleton(){              
    }        
    private static class SingletonContainer{        
        private static Singleton instance = new Singleton();        
    }        
    public static Singleton getInstance(){        
        return SingletonContainer.instance;        
    }        
}

 

推荐使用的三种无线程安全问题的单例模式

原文:https://www.cnblogs.com/mars-zyt/p/10059029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!