枚举编写单例是可以保证在多线程中的安全性

package chapter02;

public class TestSingleton {
private TestSingleton() {
}

public static TestSingleton getInstance() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

// 通过枚举返回当前类的实例
return Singleton.INSTANCE.getInstance();
}

private enum Singleton {
INSTANCE;

private TestSingleton singleton;

// 私有的构造方法
private Singleton() {
// 在类加载的时候执行一次
System.out.println("对象创建");

singleton = new TestSingleton();
}

public TestSingleton getInstance() {

return singleton;
}
}
}

转载于:https://www.cnblogs.com/Koma-vv/p/9642563.html

你可能感兴趣的:(java)