《Effective Java》上所推荐的一种写法。先上代码:
package com.pn.thread;
public class SingletonInner {
private SingletonInner() {}
public static Singleton getInstance() {
return Singleton.singleton;
}
private static class Singleton{
private static Singleton singleton = new Singleton();
}
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
// pool.execute(()->{System.out.println(SingletonInner.getInstance().hashCode());});
new Thread(() -> {System.out.println(SingletonInner.getInstance().hashCode());}, String.valueOf(i)).start();
}
}
}
这种写法是懒汉式的获取,内部类是私有的,并且无需同步锁,没有性能缺陷。