方法一、使用静态内部类(线程安全、懒加载)
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;
}
}
本文介绍两种基于单例模式实现线程池的方法:一是使用静态内部类,确保线程安全并支持懒加载;二是利用枚举特性,不仅简化实现还增强了安全性,防止序列化或反射破坏单例。
1213

被折叠的 条评论
为什么被折叠?



