欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot:task

程序员文章站 2022-06-16 08:05:22
...
TaskPool.java
==============================================
@Configuration
@EnableAsync
public class TaskPool {

    @Bean("TaskPool-1")
    public Executor myTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(10);
        executor.setKeepAliveSeconds(10);
        executor.setThreadNamePrefix("TaskPool-1-");

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
==============================================
TaskServiceImpl.java
==============================================
@Service
public class TaskServiceImpl implements TaskService {

    @Async("TaskPool-1")
    public void runTask(int i) throws InterruptedException{
        System.out.println("i = [" + i + "]");
    }

}
相关标签: springboot task