package com.seengene.ar.conent.restful.restful.test;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* @auther a123
* @create 2018-02-24 15:40
* @desc
*/
@Configuration
@ComponentScan("com.seengene.ar.conent.restful.restful.test")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
package com.seengene.ar.conent.restful.restful.test;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* @auther a123
* @create 2018-02-24 15:40
* @desc
*/
@Configuration
@ComponentScan("com.seengene.ar.conent.restful.restful.test")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
@Autowired
private AsyncTaskService asyncTaskService;
@Test
public void contextLoads() {
for(int i = 0; i < 10; i ++){
asyncTaskService.executeAsyncTask(i);
asyncTaskService.executeAsyncTaskPlus(i);
}
}
运行结果
执行异步任务: 0
执行异步任务+1: 2
执行异步任务+1: 3
执行异步任务: 2
执行异步任务: 1
执行异步任务+1: 1
执行异步任务+1: 5
执行异步任务: 4
执行异步任务+1: 4
执行异步任务: 3
执行异步任务+1: 7
执行异步任务: 6
执行异步任务+1: 6
执行异步任务: 5
执行异步任务+1: 9
执行异步任务: 8
执行异步任务+1: 8
执行异步任务: 7
执行异步任务+1: 10
执行异步任务: 9