springboot:task

阅读更多
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)