饱汉模式
//lazy
class LazyPerson {
private static volatile LazyPerson person;
private LazyPerson(){}
public static LazyPerson getSingleton() {
if (person == null) {
synchronized (LazyPerson.class) {
if (person ==null) {
person = new LazyPerson();
}
}
}
return person;
}
}
饿汉模式
//hungry
class HungryPerson {
private HungryPerson(){}
private static HungryPerson hungryPerson = new HungryPerson();
public static HungryPerson getHungryPerson() {
return hungryPerson;
}
}
饱汉模式利用Java的类加载机制保证线程安全,而饿汉模式则需要使用volatile和synchronized以及双重检查机制来保证线程安全。
测试代码
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
HungryPerson hungryPerson = HungryPerson.getHungryPerson();
System.out.println(hungryPerson);
HungryPerson hungryPerson1 = HungryPerson.getHungryPerson();
System.out.println(hungryPerson1);
System.out.println(hungryPerson == hungryPerson1);
/*//lazy start
new Thread(()-> {
Person person = Person.getSingleton();
System.out.println(person);
}).start();
new Thread(() -> {
Person person = Person.getSingleton();
System.out.println(person);
}).start();
// lazy end*/
}
}
来源:CSDN
作者:点不点外卖
链接:https://blog.csdn.net/hansirl/article/details/104310466