面试题(单例模式两种写法)

来源:互联网 发布:弹奏音乐的软件 编辑:程序博客网 时间:2024/05/22 13:05


第一种形式:饿汉式单例

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


第二种形式:懒汉式单例

public class Singleton {      private static Singleton instance = null;       private Singleton() {}       public static synchronized Singleton getInstance(){          if (instance==null) instance=newSingleton();          return instance;       }  }  

 


区别:

<strong>“懒汉式”是在你真正用到的时候才去建这个单例对象,线程安全</strong>
<strong>“饿汉式”是在不管你用的用不上,一开始就建立这个单例对象:比如:有个单例对象,线程不安全</strong>


0 0
原创粉丝点击