public class SingleThreadPoolExecutor {
private static final int CORE_SIZE = Runtime.getRuntime().availableProcessors();
private static final int MAX_SIZE = CORE_SIZE * 2;
/**
* 1.共享可见
* 2.禁止指令重排
*/
private static volatile ThreadPoolExecutor threadPoolExecutor;
/**
* 构造器私有化
* */
private SingleThreadPoolExecutor() {
throw new RuntimeException("禁止反射调用!");
}
/**
* 双重检测锁
* 1.防止高并发下线程争夺共享资源
* 2.提高效率
* */
public static ThreadPoolExecutor getThreadPoolExecutor() {
if (threadPoolExecutor == null) {
synchronized(SingleThreadPoolExecutor.class) {
if (threadPoolExecutor == null) {
threadPoolExecutor = new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
}
}
}
return threadPoolExecutor;
}
}
单例模式-懒加载
于 2024-09-18 15:36:01 首次发布