https://v.qq.com/x/page/e0364ung5zp.html
講的不錯, 關於 餓漢式單例模式
html
code安全
Student 類:多線程
package com.test;
//單例模式之 餓漢 模式 eager singleton
public class Student {
//構造函數私有,別人沒法 new 實例
private Student(){}
//本身造一個實例
private static Student student = new Student();//餓漢模式:直接 new 了一個 instance。線程安全
public static Student getStudent()
{
return student;
}
}
測試類:
package com.test;
//單例模式,保證類在內存中只有一個實例
public class StudentTest {
public static void main(String[] args) {
Student student1 = Student.getStudent();
Student student2 = Student.getStudent();
System.out.println(student1);
System.out.println(student2);
System.out.println(student1 == student2);
}
}
======結果===========
com.test.Student@7852e922
com.test.Student@7852e922
true
上面是 餓漢式 單例模式。函數
下面看看懶漢式:測試
Person 類:
spa
package com.test;
//單例模式之 懶漢 模式 lazy singleton
public class Person {
private Person() {};
private static Person person; //懶漢模式並不直接 new instance
public static Person getInstance()
{
if (person == null) //這裏其實不是線程安全的。後續能夠 enhance
{
person = new Person();
線程
return person;//只有當調用getInstance的時候,纔回去初始化這個單例。
}
return person;
}
}
code
測試類:htm
package com.test;
public class PersonDemo {
public static void main(String[] args) {
Person person1 = Person.getInstance();
Person person2 = Person.getInstance();
System.out.println(person1 == person2);
}
}
=======總結==========內存
餓漢就是類一旦加載,就把單例初始化完成,保證getInstance的時候,單例是已經存在的了。
而懶漢比較懶,只有當調用getInstance的時候,纔回去初始化這個單例。
餓漢式天生就是線程安全的,能夠直接用於多線程而不會出現問題,
懶漢式自己是非線程安全的,爲了實現線程安全有幾種寫法。
package com.test;
//單例模式之 懶漢 模式 lazy singleton
public class Person {
private Person() {};
private static Person person; //懶漢模式並不直接 new instance
public static
synchronized
Person getInstance()
//這裏加上 synchronized 保證線程安全
{
if (person == null)
{
person = new Person();//只有當調用getInstance的時候,纔回去初始化這個單例。
return person;
} return person; }}