/**
* 单例模式 静态内部类(安全)
*/
class Singleton {
// 1.私有化构造方法
private Singleton(){};
// 2.写静态内部类,创建实例
private static class SingletonInstance{
private static final Singleton singleton = new Singleton();
}
// 3.对外暴露一个get方法,返回实例
public static Singleton getInstance(){
return SingletonInstance.singleton;
}
}
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 10000; i++){
new Thread(()->{
Singleton instance = Singleton.getInstance();
System.out.println(instance.hashCode());//获取的所有实例的hashCode应该都是一样的
}).start();
}
}
}
优点:使用内部静态类延迟加载的特点,效率高,线程安全