下面是我的代碼。
使用我下面的代碼,沒有創建不同的執行緒 ID。
輸出具有相同的執行緒 ID。
@Controller
@RequestMapping(value = "/Main")
public class MyController
{
@Autowired
private MyService myService;
@PostMapping("/Sub")
@ResponseBody
public String readInput(@RequestBody String name)
{
for (int i = 0;i<5;i )
{
myService.asyncMethod();
}
return "Success";
}
}
使用我下面的代碼,沒有創建不同的執行緒 ID。
@Repository
@Configuration
@EnableAsync
public class MyService {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}
@Async("threadPoolTaskExecutor")
public void asyncMethod() {
System.out.println("Thread " Thread.currentThread().getId() " is running");
}
}
uj5u.com熱心網友回復:
首先,無法通過執行緒id來判斷執行緒池是否被使用。可以設定執行緒前綴,通過日志判斷
- 配置執行緒池
@Slf4j
@Configuration
public class ThreadExecutorConfig {
@Autowired
private ThreadPoolProperties threadPoolProperties;
@Bean(name = "taskExecutor")
public ExecutorService executorService() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
executor.setQueueCapacity(threadPoolProperties.getQueueSize());
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("myThread-");
executor.initialize();
log.info("threadPoolConfig;corePoolSize:[{}];maxPoolSize:[{}];queueSize:[{}]",
threadPoolProperties.getCorePoolSize(),
threadPoolProperties.getMaxPoolSize(),
threadPoolProperties.getQueueSize());
return executor.getThreadPoolExecutor();
}
}
- 在方法上使用@Async 注釋
@Async(value = "taskExecutor")
@Override
public void asyncSave(OperationLogModel entity) {
if (log.isDebugEnabled()) {
log.debug("thread:{};entity:{}", Thread.currentThread().getName(), entity.toString());
}
entity.setCreateTime(LocalDateTime.now());
super.save(entity);
}
- 查看日志

uj5u.com熱心網友回復:
好問題!答案在ThreadPoolTask??Executor 中。它的默認corePoolSize值為 1。
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(3);//or any (positive) integer that suits you.
return threadPoolTaskExecutor;
}
..會像我們預期的那樣表現得更好:
Thread 127 is running
Thread 128 is running
Thread 128 is running
Thread 129 is running
Thread 127 is running
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/369847.html
上一篇:變壓器中的饋送解碼器輸入
