简单且实用的多线程@EnableAsync(国庆day2)

    科技2022-07-21  118

    使用多线程,往往是创建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.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 等待所有任务结束后再关闭线程池 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("异步执行,我不等你了,先走异步!"); } }

    执行结果:先调用的异步方法,在没有执行完异步方法的情况下,执行了方法调用之后的输出语句。

    Processed: 0.013, SQL: 8