转载地址没了...
使用
@Resource(name = "brianThreadPool")
private ThreadPoolTaskExecutor executor;
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("Hello World!");
}
});
配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author
* @date 2020/2/21 11:47
* @description 线程池配置类
*/
@EnableAsync
@Configuration
public class ExecutorConfig {
@Value("${executor.size.core:10}")
private Integer core;
@Value("${executor.size.max:20}")
private Integer max;
@Value("${executor.size.queue:100}")
private Integer queue;
@Value("${executor.keepalive.time:60}")
private Integer keepalive;
@Bean
public ThreadPoolTaskExecutor brianThreadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(core);
//最大线程数
executor.setMaxPoolSize(max);
//队列中最大的数
executor.setQueueCapacity(queue);
//线程名称前缀
executor.setThreadNamePrefix("brianThreadPool_");
//rejectionPolicy:当pool已经达到max的时候,如何处理新任务
//callerRuns:不在新线程中执行任务,而是由调用者所在的线程来执行
//对拒绝task的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//线程空闲后最大的存活时间(秒)
executor.setKeepAliveSeconds(keepalive);
//初始化加载
executor.initialize();
return executor;
}
}