使用某种类型的请求限制(即每秒请求数)可能比同时执行一个方法的线程数更好。例如,直接使用Guava的RateLimiter,或者事件添加对Spring
AOP的声明性支持。
如果您仍然想使用线程,我的建议是使用ExecutorService:
@Servicepublic class documentService { private final ExecutorService executor; @Autowired public documentService( @Value("${some.config.property}") int maxConcurrentThreads) { // will allow only the given number of threads executor = Executors.newFixedThreadPool(maxConcurrentThreads); } private void doReplacementWithLimitedConcurrency(String s, int i){ Future<?> future = executor.submit(() -> doReplacement(s, i)); future.get(); // will block until a thread picks up the task// and finishes executing doReplacement } private void doReplacement(String s, int i){ } // other methods @PreDestroy public void performThreadPoolCleanup() throws Exception { executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); executor.shutdownNow(); }}


