public class Singleton { private static volatile Singleton instance; public static Singleton getInstance() { if (null == instance) { synchronized (Singleton.class) { if (null == instance) { instance = new Singleton(); } } } return instance; }}
// 利用私有静态内部类public class Singleton2 { private Singleton2() { } private static class Singleton2Holder { private static Singleton2 instance = new Singleton2(); } public static Singleton2 getInstance() { return Singleton2Holder.instance; }}
// 测试import java.util.concurrent.CyclicBarrier;import java.util.concurrent.BrokenBarrierException;public class Singleton1Test { private static int SIZE = 10; private static CyclicBarrier cb; public static void main(String[] args) { cb = new CyclicBarrier(SIZE); for (int i = 0; i < SIZE; i++) { new InnerThread().start(); } } static class InnerThread extends Thread { public void run() { try { cb.await(); Singleton1 instance = Singleton1.getInstance(); System.out.println(instance + "\t" + this.getName() + ""); } catch (BrokenBarrierException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }}