使用线程池,更新文章阅读数
1、编写线程池配置类
在这里插入代码片
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean("taskExecutor")
public Executor asyncServiceExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
threadPoolTaskExecutor.setCorePoolSize(5);
threadPoolTaskExecutor.setMaxPoolSize(20);
threadPoolTaskExecutor.setQueueCapacity(Integer.MAX_VALUE);
threadPoolTaskExecutor.setKeepAliveSeconds(60);
//等待所有任务都执行完,再关闭线程池
threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
2、编写线程任务类
在这里插入代码片
@Component
public class ThreadServiceB {
@Async("taskExecutor")
public void updateCount() throws InterruptedException {
Thread.sleep(3000);
System.out.println("阅读数+1------------");
}
}
3、使用线程任务
在这里插入代码片
@Autowired
private ThreadServiceB threadServiceB;
@Trace
@Tags(@Tag(key = "getUserById",value = "arg[0]"))
public String getUserById(Long userId) throws InterruptedException {
//Thread.sleep(30000);
threadServiceB.updateCount();
return "123";
}