public class ThreadSafeSingleton { /** *volatile 具有synchronized的可见特性, *也就是说线程能够自动发现volatitle修饰属性的最新值 */ private volatile static ThreadSafeSingleton instance = null; private ThreadSafeSingleton() { } public ThreadSafeSingleton getInstance() { if (instance == null) { synchronized (ThreadSafeSingleton.class) { instance = new ThreadSafeSingleton(); } } return instance; } }
另外一种写法
public class LazyLoadedSingelton { private LazyLoadedSingelton() { } private static class LazyHolder { private final static LazyLoadedSingelton instance = new LazyLoadedSingelton(); } public static LazyLoadedSingelton getInstance() { return LazyHolder.instance; } }