方法一、使用静态内部类(线程安全、懒加载)
public class SingletonThreadPool {
private ExecutorService threadPool;
private SingletonThreadPool() {
threadPool = Executors.newCachedThreadPool();
}
private static class SingletonContainer {
private static SingletonThreadPool instance = new SingletonThreadPool();
}
public static SingletonThreadPool getInstance() {
return SingletonContainer.instance;
}
public ExecutorService getThreadPool() {
return threadPool;
}
}
方法二、使用枚举实现(JDK1.5+支持,《Effective Java》推荐方式)
相比于方法一,此种方式可避免序列化或反射破坏单例。
public enum SingletonThreadPool {
INSTANCE;
private ExecutorService threadPool;
private SingletonThreadPool() {
threadPool = Executors.newCachedThreadPool();
}
public ExecutorService getThreadPool() {
return threadPool;
}
}