设计线程安全的单例模式

题目:

实现lazy-init的单例类,要保证线程安全。

解答:

package com.interview.pattern.singleton;
 
public class SingletonDemo {
    private static volatile SingletonDemo instance;
 
    private SingletonDemo(){
 
    }
 
    public static SingletonDemo getInstance(){
        if(instance == null){
            synchronized(SingletonDemo.class){
                if(instance == null){
                    instance = new SingletonDemo();
                }
            }
        }
 
        return instance;
    }
}