面试题答案
一键面试关键配置
- 引入依赖:确保项目中引入了Spring相关依赖,如
spring-context
等基础依赖。 - 线程池配置类:通过
@Configuration
注解定义一个配置类,在其中定义ThreadPoolTaskExecutor
的Bean。例如:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
public class ThreadPoolConfig {
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
executor.initialize();
return executor;
}
}
代码实现思路
- 获取线程池实例:在需要动态调整线程池参数的地方,通过依赖注入获取
ThreadPoolTaskExecutor
实例。例如在一个Service中:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
public void adjustThreadPool(int corePoolSize, int maxPoolSize) {
taskExecutor.setCorePoolSize(corePoolSize);
taskExecutor.setMaxPoolSize(maxPoolSize);
}
}
- 动态调整:在合适的业务逻辑处调用
adjustThreadPool
方法,传入需要调整的核心线程数和最大线程数的值,即可实现动态调整。例如在Controller中:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/adjustThreadPool")
public String adjustThreadPool(@RequestParam int corePoolSize, @RequestParam int maxPoolSize) {
myService.adjustThreadPool(corePoolSize, maxPoolSize);
return "ThreadPool adjusted successfully";
}
}
另外,还可以通过@Value
注解从配置文件(如application.properties
或application.yml
)中读取初始的核心线程数和最大线程数,并且在运行时通过修改配置文件并触发Spring的配置刷新机制(如使用Spring Cloud Config或@RefreshScope
等)来动态调整线程池参数。