Spring Boot多线程
TaskConfig.java
创建线程池与核心线程数,最大线程数
package com.yhw.demo;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/**
* 描述该类- JPA
*
* @author zhoufei
* @class: TaskConfig
* @date 2021/1/20 11:38
* @Verson 1.0 -2021/1/20 11:38
* @see
*/
@Configuration
@EnableAsync //1 开启异步
public class TaskConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
// 设置线程池
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// 核心线程数
taskExecutor.setCorePoolSize(25);
// 最大线程数
taskExecutor.setMaxPoolSize(50);
// 阻塞队列
taskExecutor.setQueueCapacity(100);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
异步方法的接口实现
DemoService.java
package com.yhw.demo;
/**
* 描述该类- JPA
*
* @author zhoufei
* @class: DemoService
* @date 2021/1/20 11:42
* @Verson 1.0 -2021/1/20 11:42
* @see
*/
public interface DemoService {
void asyncTask1(Integer i);
}
DemoServiceImpl.java
package com.yhw.demo;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* 描述该类- JPA
*
* @author zhoufei
* @class: DemoService
* @date 2021/1/20 11:42
* @Verson 1.0 -2021/1/20 11:42
* @see
*/
@Service
public class DemoServiceImpl implements DemoService {
@Async // 1声明方法为异步方法
@Override
public void asyncTask1(Integer i) {
try {
//间隔1秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行异步任务A: " + i);
}
}
DemoController.java
package com.yhw.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 描述该类- JPA
*
* @author zhoufei
* @class: DemoService
* @date 2021/1/20 11:42
* @Verson 1.0 -2021/1/20 11:42
* @see
*/
@RestController
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping("t1")
public Object t1() {
for (int i = 1; i < 100; i++) {
demoService.asyncTask1(i);
}
return "ok";
}
}
执行结果
执行异步任务A: 5
执行异步任务A: 3
执行异步任务A: 1
执行异步任务A: 2
执行异步任务A: 12
执行异步任务A: 13
执行异步任务A: 17
执行异步任务A: 15
执行异步任务A: 4
执行异步任务A: 7
执行异步任务A: 11
执行异步任务A: 6
执行异步任务A: 8
执行异步任务A: 10
执行异步任务A: 23
执行异步任务A: 22
执行异步任务A: 9
```![在这里插入图片描述](https://img-blog.csdnimg.cn/9b643e898f4b4605b2b842101d3a9b67.png)
## 总结
使用@Async表名实现方法为异步,通过 睡眠的方式实现异步