1.配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolTaskExecutorConfig {
@Bean(name = "threadPoolTaskExecutor")
@Primary
public ThreadPoolTaskExecutor mallchatExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);//核心线程 10
executor.setMaxPoolSize(5);//最大线程 10
executor.setQueueCapacity(200);//队列 200
executor.setThreadNamePrefix(executor.getThreadNamePrefix());//线程名称
executor.setWaitForTasksToCompleteOnShutdown(true);//线程优雅停机
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//用于获取线程运行时异常
executor.initialize();
return executor;
}
}
2.使用
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
for(int i=0;i<10;i++){
threadPoolTaskExecutor.execute(() -> {
try {} catch (Exception e) {
e.printStackTrace();
}});
}
if (orders.isEmpty()) {
Thread.sleep(5000);
}
logger.info("线程数->"+threadPoolTaskExecutor.getPoolSize());