线程安全的写法:
public class Singleton{
//私有化构造器
private Singleton(){}
private static Singleton instance = null;
//存在多个线程对共享数据instance的操作
//方式一:synchronized关键字
// public static synchronized Singleton getInstance() {
//
// if(instance == null) {
// instance = new Singleton();
// }
// return instance;
// }
//方式二:效率更高。如果已经存在实例对象,就告诉后面的线程已经有了,不用再等待,直接返回instance
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}