1. public class Singleton {
    2. /*
    3. volatile 修饰,
    4. singleton = new Singleton() 可以拆解为3步:
    5. 1、分配对象内存(给singleton分配内存)
    6. 2、调用构造器方法,执行初始化(调用 Singleton 的构造函数来初始化成员变量)。
    7. 3、将对象引用赋值给变量(执行完这步 singleton 就为非 null 了)。
    8. 若发生重排序,假设 A 线程执行了 1 和 3 ,还没有执行 2,B 线程来到判断 NULL,B 线程就会直接返回还没初始化的 instance 了。
    9. volatile 可以避免重排序。
    10. */
    11. private volatile static Singleton singleton;
    12. private Singleton() {
    13. }
    14. public static Singleton getSingleton() {
    15. if (singleton == null) {
    16. synchronized (Singleton.class) {
    17. if (singleton == null) {
    18. singleton = new Singleton();
    19. }
    20. }
    21. }
    22. return singleton;
    23. }
    24. }