public enum SingleInstance {
instance;
SingleInstance() {
System.out.println("new SingleInstance");
}
public void method(){
System.out.println("SingleInstance method");
}
}
测试代码
public class Main {
public static void main(String[] args) {
System.out.println("SingleInstance调用之前");
for(int i=0;i<10;i++){
new Thread(SingleInstance.instance::method).start();
}
}
}
结果
SingleInstance调用之前
new SingleInstance
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
SingleInstance method
Process finished with exit code 0
所以枚举单例是线程安全并且是用时再加载的