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; }}