线程池配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author YanYu
* @create 2021-02-01 10:28
*/
@EnableAsync
@Configuration
public class ThreadPoolConfig {
/**
* 线程核心数
*/
private int corePoolSize = 10;
/**
* 线程最大数
*/
private int maxPoolSize = 10;
/**
*任务容量
*/
private int queueCapacity = 20;
/**
* 允许空闲时间,默认60
*/
private int keepAlive = 100;
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
threadPoolTaskExecutor.setKeepAliveSeconds(keepAlive);
threadPoolTaskExecutor.setThreadNamePrefix("Thread-");
//设置拒绝策略 当线程数达到最大时,如何处理新任务
//CallerRunsPolicy 不由线程池中线程执行,由调用者所在线程执行
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//所有任务完成后再关闭线程池
threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
return threadPoolTaskExecutor;
}
}
异步方法
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author YanYu
* @create 2021-02-01 10:43
*/
@Component
public class AsyncTaskTest {
@Async("taskExecutor")
public void print(String str){
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":print " + str);
}
}
}
测试
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author YanYu
* @create 2021-02-01 11:11
*/
@RestController
public class TestController {
@Autowired
AsyncTaskTest asyncTaskTest;
@RequestMapping("/test")
public void test(){
asyncTaskTest.print("hello world");
}
}
结果
连续访问几次发现不同的线程在打印hello world