springboot中维护线程池,使用配置线程池中的线程操作

1.配置线程池类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @描述 :配置线程池
 * @创建人 :zj
 * @创建时间 2018/8/8
 * @修改人和其它信息
 */
@Configuration
public class ThreadPoolExecutorConfig {
    /**
     * 配置线程池
     *
     * @return
     */
    @Bean(name = "myPoolExecutor")
    public ThreadPoolTaskExecutor getMyThreadPoolExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        /**
        corePoolSize:线程池维护线程的最少数量

		keepAliveSeconds:允许的空闲时间
		
		maxPoolSize:线程池维护线程的最大数量
		
		queueCapacity:缓存队列
		
		rejectedExecutionHandler:对拒绝task的处理策略
        */
        taskExecutor.setCorePoolSize(20);
        taskExecutor.setMaxPoolSize(200);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.setKeepAliveSeconds(200);
        //这里可以定义线程池名字
        taskExecutor.setThreadNamePrefix("myPoolExecutor");
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }
}

2.启动类配置

@SpringBootApplication
@EnableScheduling//开启定时调度
@EnableAsync //开启异步注解功能
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication .class, args);
    }

}

3.使用线程池。

    @Async("myPoolExecutor")
    public void push() {
      .........
      //查看当前线程名字
      //        log.info("当前方法内部线程名称:{}!", Thread.currentThread().getName());

    }

你可能感兴趣的:(springboot中维护线程池,使用配置线程池中的线程操作)