说明
spring-boot引入线程不需要再添加额外的jar
1、spring-boot主启动类添加注解
在spring-boot的主启动类上加添加注解@EnableAsync
@SpringBootApplication(scanBasePackages = {"com.test.test"})
@EnableScheduling //启动定时任务
@EnableTransactionManagement // 开启事务
@Slf4j
@EnableAsync
public class MainLuncher {
public static void main(String[] args) {
SpringApplication.run(MainLuncher .class, args);
}
}
2、定义线程池
@Configuration
@EnableAsync
public class TaskExecutePool {
@Bean
public Executor taskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
TaskThreadPoolConfig config = new TaskThreadPoolConfig(5,10,25,60);
//初始线程大小
executor.setCorePoolSize(config.getCorePoolSize());
//最大线程大小
executor.setMaxPoolSize(config.getMaxPoolSize());
//设置队列长度
executor.setQueueCapacity(config.getQueueCapacity());
//设置多长时间,线程回收
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
private class TaskThreadPoolConfig{
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
public TaskThreadPoolConfig(int corePoolSize,int maxPoolSize,int keepAliveSeconds,int queueCapacity){
this.corePoolSize = corePoolSize;
this.maxPoolSize = maxPoolSize;
this.keepAliveSeconds = keepAliveSeconds;
this.queueCapacity = queueCapacity;
}
public int getCorePoolSize() {
return corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public int getKeepAliveSeconds() {
return keepAliveSeconds;
}
public int getQueueCapacity() {
return queueCapacity;
}
}
}
3、创建任务类
@Component
@Slf4j
public class AsyncTask {
//taskAsyncPool即配置线程池的方法名,此处如果不写自定义线程池的方法名,会使用默认的线程池
@Async("taskAsyncPool")
public Future<String> syncMethod(Parmater p1) throws InterruptedException{
//do some thing
return new AsyncResult<>("success");
}
}
4、调用任务类
//这里是用测试类来调用
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MainLuncher.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class SpringbootApplicationTest {
@Resource
private AsyncTask task;
@Test
public void AsyncTaskTest(){
try {
Parameter p = new Parameter();
//异步服务
Future<String> task1 = task.syncMethod(p1);
log.info("AsyncTaskTest syncMethodexecuting...");
while(true) {
if(task1.isDone()) {
log.info("Task1 result: {}", task1.get());
break;
}
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
log.info("AsyncTaskTest main done");
}
}