SpringBoot启动多线程
新建一个线程池的配置类,需要被spring扫描到。
@Configuration @EnableAsync public class ThreadExecutorConfig { @Bean public Executor executor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(20);//线程池维护线程的最少数量 executor.setMaxPoolSize(50);//线程池维护线程的最大数量 executor.setQueueCapacity(15);//缓存队列 executor.setThreadNamePrefix("ssmsExecutor-"); /** * 对拒绝task的处理策略 rejection-policy:当pool已经达到max size的时候,如何处理新任务 CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行 */ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.setKeepAliveSeconds(60);//允许的空闲时间 executor.initialize(); return executor; } }
添加一个普通类,里面编写需要执行的方法,方法加上@Async注解,调用方法时自动启动线程。
@Component public class BmtOrderThread { @Async public Future<Map<String,Object>> test1() { Map<String,Object> result=new HashMap<String,Object>(); return new AsyncResult<>(result); } @Async public void test2() { System.out.println("hello"); } }
调用有返回值的线程方法:
public static void main(String[] args) { List<Future<Map<String,Object>>> futures = new ArrayList<>();//存线程的返回结果 //以下调用会启动线程进行执行,多线程并发 Future<Map<String,Object>> res1=bmtOrderThread.test1(); futures.add(res1); Future<Map<String,Object>> res2=bmtOrderThread.test1(); futures.add(res2); //会等待所有线程都执行结束,拿到结果 try { for(Future future:futures) { Object obj=future.get(); Map<String,Object> result=(Map<String,Object>)obj; } } catch(Exception e) { e.printStackTrace(); } }
调用无返回值的线程方法:
public static void main(String[] args) { //以下方法会启动多线程,并发执行 bmtOrderThread.test1(); bmtOrderThread.test1(); bmtOrderThread.test1(); }
参考的博客:
https://blog.csdn.net/qq_39385706/article/details/79365849
https://blog.csdn.net/weixin_38399962/article/details/82146480
https://www.cnblogs.com/guyezhai/p/5776357.html