枚举编写单例是可以保证在多线程中的安全性
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;
		}
	}
}
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号