SpringBoot_Thread
第一步
spring:
task:
execution:
pool:
core-size: 10
max-size: 20
queue-capacity: 40
keep-alive: 60
thread-name-prefix: thread-
第二步
@Configuration
@EnableAsync
public class ThreadConfig implements AsyncConfigurer {
@Value("${spring.task.execution.pool.core-size}")
private Integer coreSize;
@Value("${spring.task.execution.pool.max-size}")
private Integer maxSize;
@Value("${spring.task.execution.pool.queue-capacity}")
private Integer queueCapacity;
@Value("${spring.task.execution.pool.keep-alive}")
private Integer keepAlive;
@Value("${spring.task.execution.thread-name-prefix}")
private String threadNamePrefix;
@Bean("getAsyncExecutor")
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(coreSize);
executor.setMaxPoolSize(maxSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAlive);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
第三步
public interface IThreadService {
void getData();
void sysData(int i);
}
第四步
@Service
public class ThreadServiceImpl implements IThreadService {
@Resource
private Executor executor;
@Async("getAsyncExecutor")
@Override
public void getData() {
CountDownLatch mainMonitor = new CountDownLatch(1);
CountDownLatch childMonitor = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
int j = i;
executor.execute(() -> {
try {
mainMonitor.await();
System.out.println("第" + j + "完成任务" + Thread.currentThread().getName());
childMonitor.countDown();
} catch (Exception e) {
e.printStackTrace();
}
});
}
try {
childMonitor.await();
mainMonitor.countDown();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("任务释放" + Thread.currentThread().getName());
}
@Async("getAsyncExecutor")
@Override
public void sysData(int i) {
System.out.println("线程" + Thread.currentThread().getName() + " 执行异步任务:" + i);
}
}
第五步
@Controller
public class ThreadController {
@Resource
private IThreadService threadService;
@PostMapping("/getData")
@ResponseBody
public boolean getData() {
threadService.getData();
return true;
}
@PostMapping("/sysData")
@ResponseBody
public boolean sysData() {
for (int i = 0; i < 10; i++) {
threadService.sysData(i);
}
return true;
}