线程池具有以下属性:
核心线程数:CORE_POOL_SIZE
最大线程数:MAX_POOL_SIZE
线程保持活跃时间:KEEP_ALIVE_SECONDS
时间单位:TimeUnit.MILLISECONDS
任务队列:LinkedBlockingQueue,容量为QUEUE_CAPACITY
线程工厂:为每个新线程设置名称前缀"lwc-pool-"和一个自增的编号
拒绝策略:ThreadPoolExecutor.DiscardPolicy,即直接丢弃任务不做处理
这个线程池用于执行提交的Runnable任务。
package com.sdx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@Configuration
public class ThreadPoolConfig {
/**
* 核心线程池大小
*/
private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
/**
* 最大可创建的线程数
*/
private static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
/**
* 队列最大长度
*/
private static final int QUEUE_CAPACITY = 50000;
/**
* 线程池维护线程所允许的空闲时间
*/
private static final int KEEP_ALIVE_SECONDS = 60;
@Bean
public ExecutorService executorService(){
AtomicInteger c = new AtomicInteger(1);
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(QUEUE_CAPACITY);
return new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_SECONDS,
TimeUnit.MILLISECONDS,
queue,
r -> new Thread(r, "lwc-pool-" + c.getAndIncrement()),
new ThreadPoolExecutor.DiscardPolicy()
);
}
}