所有栏目 | 云社区 美国云服务器[国内云主机商]
你的位置:首页 > 云社区 » 正文

单例模式中的懒汉式和饿汉式有什么区别?

发布时间:2020-04-12 08:48:13

资讯分类:饿汉式  懒汉式  单例模式  区别  懒汉  对象  创建
单例模式中的懒汉式和饿汉式有什么区别?

饿汉式: public class Singleton{ private static Singleton singleton = new Singleton (); private Singleton (){} public Singleton getInstance(){return singletion;} } 懒汉式: public class Singleton{ private static Singleton singleton = null; public static synchronized synchronized getInstance(){ if(singleton==null){ singleton = new Singleton(); } return singleton; } } 比较: 饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变 懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的 推荐使用第一种

留言与评论(共有 0 条评论)
   
验证码:
Top