ThreadPoolTaskConfig.java

/**
 * 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
 * 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
 * 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝
 *
 * @author Jensen Zhan
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {

    /**
     * 默认线程数
     */
    private static final int CORE_POOL_SIZE = 20;
    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 100;
    /**
     * 允许线程空闲时间(单位:默认为秒)
     */
    private static final int KEEP_ALIVE_TIME = 10;
    /**
     * 缓冲队列大小
     */
    private static final int QUEUE_CAPACITY = 200;
    /**
     * 线程池名前缀
     */
    private static final String THREAD_NAME_PREFIX = "Async-Service-";

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}

 

ThreadService.java

/**
 * @author Jensen Zhan
 */
@Service
public class ThreadService {
    @Async
    public void sendMessage1() {
        for (int i = 0; i < 10000; i++) {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName());
        }
    }

    @Async
    public void sendMessage2() {
        for (int i = 0; i < 10000; i++) {
            Thread thread = Thread.currentThread();
            System.out.println(thread.getName());
        }
    }
}

 

 

OpenThread.java

/**
 * @author Jensen Zhan
 */
@Component
public class OpenThread implements ApplicationRunner {

    @Autowired
    private ThreadService threadService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        threadService.sendMessage1();
        threadService.sendMessage2();
        System.out.println("end ...");
    }
}

 

然后直接运行application

 

posted on 2020-07-02 10:10  帅过驴的袋鼠  阅读(6890)  评论(0编辑  收藏  举报