线程安全的单例模式

来源:互联网 发布:java reactor设计模式 编辑:程序博客网 时间:2024/06/07 13:56
  • 不使用锁而定义时直接初始化
    class Singleton {        private static Singleton instance= new Singleton();        private Singleton(){}        public static Singleton getInstance() {            return instance;        }    }
  • 使用synchronized修饰方法
    class Singleton {        private static Singleton instance;        private Singleton(){}        public static synchronized Singleton getInstance() {            if(instance == null)                instance = new Singleton();            return instance;        }    }
  • 双重检查锁定(Double Check Locking),使用synchronized锁定单例类
    class Singleton {        private static Singleton instance;        private Singleton(){}        public static Singleton getInstance() {            if(instance == null) {                synchronized(Singleton.class) {                    if(instance == null)                         instance = new Singleton();                }            }            return instance;        }    }
原创粉丝点击