Java多线程--Springboot线程池配置,使用@Async注解来异步执行

一、创建一个ExecutorConfig配置类

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.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 * Description: 线程池,使用时在方法上添加 @Async("myAsync")即可
 */
@Configuration
@EnableAsync
public class ExecutorConfig {
    /** 设置ThreadPoolTaskExecutor的核心池大小 */
    private static final int CORE_POOL_SIZE = 10;
    /** 设置ThreadPoolTaskExecutor的最大池大小 */
    private static final int MAX_POOL_SIZE = 200;
    /** 允许的空闲时间 */
    private static final int KEEP_ALIVE_SECONDS = 300;
    /** 设置ThreadPoolTaskExecutor的队列数量 */
    private static final int QUEUE_CAPACITY = 200;
    /** 设置线程前缀名称 */
    private static final String THREAD_NAME_PREFIX = "MyExecutor-";

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

二、使用@Async注解来异步执行

    @Async("myAsync")
    public void test(){
        System.out.println("异步执行代码块");
    }

 

你可能感兴趣的:(线程池)