使用多线程,往往是创建Thread,或者是实现runnable接口,用到线程池的时候还需要创建Executors,spring中有十分优秀的支持,就是注解@EnableAsync就可以使用多线程,@Async加在线程任务的方法上(需要异步执行的任务),定义一个线程任务,通过spring提供的ThreadPoolTaskExecutor就可以使用线程池。
1 线程池配置WebApiThreadConfig
@Configuration
@EnableAsync
public class WebApiThreadConfig {
@Resource
private ThreadConfig threadConfig
;
@Bean
public TaskExecutor
taskExecutor() {
ThreadPoolTaskExecutor executor
= new ThreadPoolTaskExecutor();
executor
.setCorePoolSize(threadConfig
.getCorePoolSize());
executor
.setMaxPoolSize(threadConfig
.getMaxPoolSize());
executor
.setQueueCapacity(threadConfig
.getQueueCapacity());
executor
.setKeepAliveSeconds(threadConfig
.getKeepAliveSeconds());
executor
.setThreadNamePrefix(threadConfig
.getThreadNamePrefix());
executor
.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
executor
.setWaitForTasksToCompleteOnShutdown(true);
return executor
;
}
}
2 创建异步方法,一个注解搞定
@Component
public class TreadTasks {
@Async("taskExecutor")
public void startMyTreadTask() throws InterruptedException
{
int i
= 10;
while (i
>=0) {
Thread
.sleep(1000);
System
.out
.println("第"+i
+"秒");
i
--;
}
}
}
3 小测一波
@RestController
public class AsyncTaskUse {
@Autowired
private TreadTasks treadTasks
;
@GetMapping("/startMysync")
public void useMySyncTask() throws InterruptedException
{
treadTasks
.startMyTreadTask();
System
.out
.println("异步执行,我不等你了,先走异步!");
}
}
执行结果:先调用的异步方法,在没有执行完异步方法的情况下,执行了方法调用之后的输出语句。