volatile 实现 单例模式

单例模式的一种实现方式,但很多人会忽略volatile关键字,因为没有该关键字,程序也可以很好的运行,只不过代码的稳定性总不是100%,说不定在未来的某个时刻,隐藏的bug就出来了。

双重校验锁

class Singleton {
    private volatile static Singleton instance;
   private Singleton (){}   public static Singleton getInstance() { if (instance == null) { syschronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }

  懒加载的优雅写法静态内部类

public class Singleton {  

        private Singleton (){}  

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

 

}

 转http://www.jianshu.com/p/195ae7c77afe 

http://cantellow.iteye.com/blog/838473

posted @ 2017-05-04 18:39  antball  阅读(1094)  评论(0编辑  收藏  举报