由于阿里开发手册提出禁用Executor创建线程池,主要原因是容易引起OOM,推荐使用ThreadPoolExecutor,自己手动创建线程池,根据实际情况设置核心线程数,防止OOM
public class ThreadTest {
/**
* ThreadPoolExecutor使用
*/
public static void main(String[] args) throws InterruptedException, IOException {
//核心线程池大小
int corePoolSize = 2;
//最大线程池大小
int maximumPoolSize = 4;
//线程最大空闲时间
long keepAliveTime = 10;
//时间单位
TimeUnit unit = TimeUnit.SECONDS;
//线程等待队列
BlockingQueue workQueue = new ArrayBlockingQueue(2);
//线程创建工厂
ThreadFactory threadFactory = new NameTreadFactory();
//拒绝策略
RejectedExecutionHandler handler = new SelfIgnorePolicy();
//创建线程(根据实际情况确定核心线程池大小)
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
workQueue, threadFactory, handler);
//预启动所有核心线程
executor.prestartAllCoreThreads();
for (int i = 1; i |