[SpringBoot] --5 asynchronous call using @Async

1 using @Asyncasynchronous calls

Start Plus @EnableAsync, need to join in on asynchronous methods @Asyncplus in approach @Asyncafter the underlying use of multi-threading technology.

1.1 demo code

@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);
	}

}
Published 675 original articles · won praise 214 · Views 140,000 +

Guess you like

Origin blog.csdn.net/weixin_42112635/article/details/104871359