一 概述
在构建线程池的时候我们可以简单的通过Executors来构建,以newFixedThreadPool为例:
public static ExecutorService executor = Executors.newFixedThreadPool(10);
二 Executors构建线程的的不足
线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的开发者更加明确线程池的运行规则,规避资源耗尽的风险。 说明:Executors返回的线程池对象的弊端如下:
1)FixedThreadPool和SingleThreadPool:
允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。
2)CachedThreadPool:
允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM。
建议的Java创建方式
Positive example 1:
//org.apache.commons.lang3.concurrent.BasicThreadFactory
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
Positive example 2:
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
//Common Thread Pool
ExecutorService pool = new ThreadPoolExecutor(5, 200,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
pool.execute(()-> System.out.println(Thread.currentThread().getName()));
pool.shutdown();//gracefully shutdown
建议的XML创建方式
Positive example 3:
<bean id="userThreadPool"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="corePoolSize" value="10" />
<property name="maxPoolSize" value="100" />
<property name="queueCapacity" value="2000" />
<property name="threadFactory" value= threadFactory />
<property name="rejectedExecutionHandler">
<ref local="rejectedExecutionHandler" />
</property>
</bean>
//in code
userThreadPool.execute(thread);
三 个人常用构建线程池的方式
public class ThreadPool {
/**
* 线程池执行器
*/
private static ThreadPoolTaskExecutor EXECUTOR = new ThreadPoolTaskExecutor();
static {
//核心线程数
EXECUTOR.setCorePoolSize(10);
//最大线程数
EXECUTOR.setMaxPoolSize(20);
//队列大小
EXECUTOR.setQueueCapacity(200);
//最大线程数 - 核心线程数 空闲存活的时间
EXECUTOR.setKeepAliveSeconds(60);
//线程中的线程名前缀
EXECUTOR.setThreadNamePrefix("common-pool-");
//线程池的拒绝策略
EXECUTOR.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//线程池的初始化
EXECUTOR.initialize();
}
/**
* 获得线程池
* @param
*/
public static ThreadPoolTaskExecutor getExecutor() {
return EXECUTOR;
}
/**
* 执行
* @param command
*/
public static void execute(Runnable command) {
EXECUTOR.execute(command);
}
}