SpringBoot学习笔记1————多线程的使用线程池
1. 配置线程池的配置
1.可以使用配置文件的方式,我这里使用的是在类里面直接配置
import org.springframework.beans.factory.annotation.Value;
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;
//标识这个是一个配置类
@Configuration
//SpringBoot里面配置异步的方式
@EnableAsync
public class ExecutorConfig {
@Bean(name = "asyncServiceExecutor")
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(5);
//配置最大线程数
executor.setMaxPoolSize(5);
//配置队列大小
executor.setQueueCapacity(99999);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("aaa-aa-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
- 写一个service,里面标识哪些方法开启异步 @Async开启异步注解
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@Service
public class DemoServiceImpl {
private int num = 0;
HashMap<String,Object> map = new HashMap<String,Object>();
@Async
public String getHello() {
num++;
map.put("aa","88888");
return "你好";
}
@Async
public String say() {
map.put("a","88888");
num++;
return "这是一个demo";
}
@Async
public String get() {
map.put("cc","88888");
num++;
return "啛啛喳喳";
}
public int getNum() {
return num;
}
public HashMap<String, Object> getMap() {
return map;
}
}
3. 我这边虽然是一个实现类,但是我做其他尝试的时候,把具体接口去掉了
下面是我的测试类,我不知道如何让主线程等待,尝试过很多次,如果大家有比较好的方式可以给我说下,谢谢
@ResponseBody
@RequestMapping(“bb”)
public String hhahah(){
HashMap<String,Object> map = new HashMap<String,Object>();
while (true){
String str1 = demoService.getHello();
String str2 = demoService.say();
String str3 = demoService.get();
if(demoService.getMap().size() == 3){
System.out.println(demoService.getMap().toString());
return "aassdaasdasdddd";
}
}
}