package com.woniu.friend.utils;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.*;
public class ThreadFactoryUtils {
// volatile 防止指令重排,和保证内存可见性
private static volatile ThreadPoolExecutor threadPoolExecutor;
// 获取当前机器的核心线程数
private final static int cpuCores = Runtime.getRuntime().availableProcessors();
// 私有化构造器
private ThreadFactoryUtils(){
}
// 单例模式创建线程池,双层判断防止并发
public static ThreadPoolExecutor getThreadPoolExecutor(){
if(threadPoolExecutor == null){
synchronized (ThreadFactoryUtils.class){
if(threadPoolExecutor == null){
threadPoolExecutor = new ThreadPoolExecutor(
cpuCores, // 核心线程数
cpuCores * 2, //最大线程数
60, // 空线程最大存活时间
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(), // 阻塞队列
new CustomThreadFactory(), // 自定义线程工厂
new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
);
}
}
}
return threadPoolExecutor;
}
static class CustomThreadFactory implements ThreadFactory {
@Override
public Thread newThread(@NotNull Runnable runnable) {
return new Thread(runnable);
}
}
}