1
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;
public class ExecutorUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorUtils.class);
private static volatile ThreadPoolExecutor threadPool = null;
private ExecutorUtils() {
}
public static void submit(Runnable runnable) {
getThreadPool().execute(runnable);
}
public static ThreadPoolExecutor getThreadPool() {
try {
if (threadPool == null) {
Class<ExecutorUtils> var0 = ExecutorUtils.class;
synchronized (ExecutorUtils.class) {
if (threadPool == null) {
int cpuNum = Runtime.getRuntime().availableProcessors();
int threadNum = cpuNum * 2;
threadPool = new ThreadPoolExecutor(threadNum, threadNum + 1, 2147833647L, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<>(Integer.MAX_VALUE), Executors.defaultThreadFactory(), new AbortPolicy() {
public void rejectedException(Runnable r, ThreadPoolExecutor e) {
super.rejectedExecution(r, e);
}
});
}
}
}
} catch (Exception e) {
LOGGER.error("创建线程池异常!===>{}", e);
}
return threadPool;
}
}
2
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTaskUtils {
private static int CAPACITY = 10000;
// 线程池核心线程数
public static int CORE_POOL_SIZE = 10;
// 线程池最大线程数
private static int MAXIMUM_POOL_SIZE = 30;
// 额外线程空状态生存时间
private static Long KEEP_ALIVE_TIME = 0L;
private static TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
private static ExecutorService threadPool;
static {
BlockingQueue<Runnable> workingQueue = new ArrayBlockingQueue<Runnable>(CAPACITY);
RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.AbortPolicy();
threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, TIME_UNIT, workingQueue,
rejectedExecutionHandler);
}
/**
* 提交任务
*
* @param runnable
* @throws CommonException
*/
public static void submit(Runnable runnable) {
threadPool.execute(runnable);
}
}
测试方法
public class ThreadPools {
private static void testss() {
ExecutorUtils.submit(() -> {
System.out.println(7);
});
for (int i = 0; i < 999; i++) {
ThreadPoolTaskUtils.submit(() -> {
System.out.println(7);
});
}
}
public static void main(String[] args) {
testss();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)