ThreadPoolExecutor
创建和管理线程池,减少内存消耗,提高执行效率。
任务执行过程
1.当线程数小于核心线程数时,创建线程;
2.当线程数大于等于核心线程数,且任务队列未满时,将任务放入任务队列;
3.当线程数大于等于核心线程数,且任务队列已满:
- 若线程数小于最大线程数,创建线程
- 若线程数等于最大线程数,执行拒绝策略(抛出异常、拒绝任务等)
任务执行API
public void execute(Runnable command)
public <T> Future<T> submit(Callable<T> task) //通过future对象的get方法获取任务的执行结果
详情参见:ThreadPoolExecutor
题外,Runtime.getRuntime().availableProcessors()
获取当前设备CPU核心数。
此处提供一个Executors工具类,使用时直接@Autowired
即可
@Bean
@Primary
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
ThreadPoolExecutor.CallerRunsPolicy callerRunsPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
executor.setRejectedExecutionHandler(callerRunsPolicy); //对拒绝task的处理策略
executor.initialize();
return executor;
}
拒绝策略支持自定义
private RejectedExecutionHandler getRejectedExecutionHandler(){
return new RejectedExecutionHandler(){
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){
if(!executor.isShutdown()){
try{ executor.getQueue().put(r); }
catch (Exception e){ e.getMessage(); }
} }}; }