SpringBoot使用多线程
1、配置文件
这里把创建线程池所需要的参数放到配置文件中
#配置核心线程数
async.executor.thread.core_pool_size = 5
# 配置最大线程数
async.executor.thread.max_pool_size = 5
# 配置队列大小
async.executor.thread.queue_capacity = 99999
# 配置线程池中的线程的名称前缀
async.executor.thread.name.prefix = async-
2、配置类
@Configuration
@EnableAsync
public class ExecutorConfig implements AsyncConfigurer {
@Value("${async.executor.thread.core_pool_size}")
private int corePoolSize;
@Value("${async.executor.thread.max_pool_size}")
private int maxPoolSize;
@Value("${async.executor.thread.queue_capacity}")
private int queueCapacity;
@Value("${async.executor.thread.name.prefix}")
private String namePrefix;
@Override
@Bean("asyncExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(corePoolSize);
//配置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//配置队列大小
executor.setQueueCapacity(queueCapacity);
//配置线程池中线程的名称前缀
executor.setThreadNamePrefix(namePrefix);
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
3、使用@Async注解进行无返回值的调用
3.1任务执行
@Service("demo")
public class Demo {
@Async("asyncExecutor")
public void executorAsync(){
System.out.println("线程" + Thread.currentThread().getName() + "执行异步线程!");
}
}
3.2测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoTest {
@Autowired
private Demo demo;
@Test
public void executorAsync() {
System.out.println("开始");
for(int i = 1; i <= 10; i++){
demo.executorAsync(i);
}
System.out.println("结束");
}
}
3.3执行结果
4、使用@Async注解进行带返回值的调用
1.用Future来接受异步方法的处理结果
@Async("asyncExecutor")
public Future<String> async() throws InterruptedException {
long start = System.currentTimeMillis();
Thread.sleep(5000);
long end = System.currentTimeMillis();
return new AsyncResult<>("线程" + Thread.currentThread().getName() + "执行异步任务共耗时:"+ (end - start));
}
2.测试类
@Test
public void async() throws ExecutionException, InterruptedException {
Future<String> future = demo.async();
// 接受异步方法结果
while (true) {
if (future.isDone()) {
System.out.println(future.get());
break;
}
}
}
3.执行结果