懒汉式单例模式,为什么要加synchronized,而且为什么前后要加两个if语句,求大神讲解!!
- public class SingletonClass {
- private static SingletonClass instance = null;
- public static SingletonClass getInstance() {
- if (instance == null) {
- synchronized (SingletonClass.class) {
- if (instance == null) {
- instance = new SingletonClass();
- }
- }
- }
- return instance;
- }
- private SingletonClass() {
- }
- }
复制代码 |
|