1 public class Singleton 2 { 3 private static Singleton singleton = new Singleton();//类加载了便初始化该单例对象 4 //之所以称之为饿汉式,因为他太急了 5 private Singleton() 6 { 7 } 8 public static Singleton getInstance() 9 { 10 return singleton; 11 } 12 }
1 public class Singleton 2 { 3 private static Singleton singleton; 4 5 private Singleton() 6 { 7 } 8 //注意这里synchronized,保证了线程安全,意思就是每次只有一个线程能够访问该方法 9 public static synchronized Singleton getInstance() 10 { 11 if(singleton == null) 12 {//当singleton要用的时候才初始化,加判断避免重复初始化,保证只new了一次 13 singleton= new Singleton(); 14 } 15 return singleton; 16 } 17 }
1 public class Singleton 2 { 3 private static Singleton instance = null; 4 5 private Singleton() 6 { 7 //dosomething 8 } 9 10 public static Singleton getInstance() 11 { 12 if(instance == null) 13 { 14 synchronized(Singleton.class)//可以思考一下,为什么这样提高效率 15 { 16 if(null == instance) 17 { 18 instance= new Singleton(); 19 } 20 } 21 } 22 return instance; 23 } 24 }