单列的意思是:每次调用的对象都是同一个
- package com.quxiao.entity;
-
- /**
- * @program: package1
- * @author: quxiao
- * @create: 2023-10-05 08:49
- **/
- public class SityEntity {
- private SityEntity() {
- System.out.println(Thread.currentThread().getName());
- }
-
- static volatile SityEntity sityEntity;
- static volatile private int[] arr;
-
- public static SityEntity getSityEntity() {
- if (sityEntity == null) {
- synchronized (SityEntity.class) {
- if (sityEntity == null) {
- arr = new int[1024];
- sityEntity = new SityEntity();
- }
- }
- }
- //如果不使用volatile,有几率导致指令重排。
- //类的创建顺序是:
- //1、开辟内存空间
- //2、执行构造方法
- //3、放入内存空间中
- //cpu在执行时,有概率这样执行:1、3、2(对于cpu来说,这三条语句都没有关联,顺序没有约定)也就是说
- //A线程还执行到1、2时,
- //B线程突然取对象,发现单列对象不是null,返回值后,一调用就会空指针
- return sityEntity;
- }
- }
在java中,反射是一个双刃剑,它极大程度上帮助了框架的使用(spring对于Bean的创建就是如此)
- Constructor
declaredConstructor = SityEntity.class.getDeclaredConstructor(null); - declaredConstructor.setAccessible(true);
- SityEntity sity1 = declaredConstructor.newInstance();