1.首先配置线程池的配置文件,在此处定义线程池的核心线程数等核心参数:
/**
* 核心线程数 = cpu 核心数 + 1
*/
private final int core = Runtime.getRuntime().availableProcessors() + 1;
@Autowired
private ThreadPoolProperties threadPoolProperties;
@Bean(name = "threadPoolTaskExecutor")
@ConditionalOnProperty(prefix = "thread-pool", name = "enabled", havingValue = "true")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(core);
executor.setMaxPoolSize(core * 2);
executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
/**
* 执行周期性或定时任务
*/
@Bean(name = "scheduledExecutorService")
protected ScheduledExecutorService scheduledExecutorService() {
return new ScheduledThreadPoolExecutor(core,
new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy()) {
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
Threads.printException(r, t);
}
};
}
2.封装静态工具类(可自定义线程Id,便于后续手动杀死该线程):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
@Component
public class ThreadPoolUtil {
private static ThreadPoolTaskExecutor threadPoolTaskExecutor;
private static final Map<String, Future<?>> taskMap = new ConcurrentHashMap<>();
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void init() {
threadPoolTaskExecutor = (ThreadPoolTaskExecutor) applicationContext.getBean("threadPoolTaskExecutor");
}
public static void executeTask(String taskId, Runnable task) {
Future<?> future = threadPoolTaskExecutor.submit(task);
taskMap.put(taskId, future);
}
public static void cancelTask(String taskId) {
Future<?> future = taskMap.get(taskId);
if (future != null) {
future.cancel(true);
taskMap.remove(taskId);
}
}
public static void shutdown() {
threadPoolTaskExecutor.shutdown();
}
}