[SpringBoot] @Async异步方法

一、在main函数的入口类上加@EnableAsync注解

 

二、在Service层定义需要异步执行的方法: (如果异步方法写在Controller里,不能异步执行

@Service

public class HelloService {

@Async

public void forMethod(){ //Controller层只能直接调此方法,才能异步执行,或者另起一个方法,调用此方法,也可以异步执行

for (int i=0; i< 900000; i++){

System.out.println("--" + i + "--");

}

}

//调用这个方法时,forMethod方法也异步执行

public void syncMethod(){

System.out.println("task 1");

forMethod();

System.out.println("task 2");

}

}

 

 

三、在Controller层调用异步方法:

@RequestMapping(value = "/sync/test", method = RequestMethod.GET)

public String syncTest(){

System.out.println("sync test started...");

helloService.forMethod();

System.out.println("sync test finished...");

return "over";

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值