本篇文章给人人带来的内容是关于springboot异步挪用的引见(附代码),有肯定的参考价值,有须要的朋侪能够参考一下,愿望对你有所协助。
同步
递次根据定义递次顺次实行,每一行递次都必须守候上一行递次实行完成以后才实行,就是在发出一个功用挪用时,在没有获得效果之前,该挪用就不返回。
异步
递次在递次实行时,不守候异步挪用的语句返回效果就实行背面的递次,当一个异步历程挪用发出后,挪用者不能马上获得效果。
同步代码
Service层:
public void test() throws InterruptedException { Thread.sleep(2000); for (int i = 0; i < 1000; i++) { System.out.println("i = " + i); } }
Controller层:
@GetMapping("test") public String test() { try { Thread.sleep(1000); System.out.println("主线程最先"); for (int j = 0; j < 100; j++) { System.out.println("j = " + j); } asyncService.test(); System.out.println("主线程完毕"); return "async"; } catch (InterruptedException e) { e.printStackTrace(); return "fail"; } }
浏览器中要求 http://localhost:8080/test
控制台打印递次:
- 主线程最先
- 打印j轮回
- 打印i轮回
- 主线程完毕
异步代码
在Service层的test要领上加上@Async
注解,同时为了是异步见效在启动类上加上@EnableAsync
注解
Service层:
@Async public void test() throws InterruptedException { Thread.sleep(2000); for (int i = 0; i < 1000; i++) { System.out.println("i = " + i); } }
Controller稳定,启动类加上@EnableAsync
:
@SpringBootApplication @EnableAsync public class AsyncApplication { public static void main(String[] args) { SpringApplication.run(AsyncApplication.class, args); } }
再次要求打印递次以下:
- 主线程最先
- 打印j轮回
- 主线程完毕
- 打印i轮回
以上就是springboot异步挪用的引见(附代码)的细致内容,更多请关注ki4网别的相干文章!