/**
* 单例模式 枚举(安全)
*/
enum Singleton {
INSTANCE;
}
public class Test {
public static void main(String[] args) {
for(int i = 0; i < 10000; i++){
new Thread(()->{
Singleton instance = Singleton.INSTANCE;
System.out.println(instance.hashCode());//获取的所有实例的hashCode应该都是一样的
}).start();
}
}
}
优点:既是线程安全的,又能防止反序列化。