【 SpringBoot 】- 5 使用 @Async 实现异步调用

1 使用 @Async 实现异步调用

启动加上 @EnableAsync,需要执行异步方法上加入 @Async 在方法上加上 @Async 之后,底层使用多线程技术。

1.1 演示代码

@RestController
@Slf4j
public class IndexController {

	@Autowired
	private UserService userService;

	@RequestMapping("/index")
	public String index() {
		log.info("##01##");
		userService.userThread();
		log.info("##04##");
		return "success";
	}

}
@Service
@Slf4j
public class UserService {

	@Async // 类似与开启线程执行..
	public void userThread() {
		log.info("##02##");
		try {
			Thread.sleep(5 * 1000);
		} catch (Exception e) {
			// TODO: handle exception
		}
		log.info("##03##");

		// new Thread(new Runnable() {
		// public void run() {
		// log.info("##02##");
		// try {
		// Thread.sleep(5 * 1000);
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
		// log.info("##03##");
		// }
		// }).start();
	}

}
@EnableAsync // 开启异步注解
@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

}
发布了675 篇原创文章 · 获赞 214 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/weixin_42112635/article/details/104871359