SpringBoot 异步调用@Async的实现

异步调用与同步调用
同步调用:一般来说,我们的程序基本上使用的都是同步调用,程序按定义的顺序依次执行的过程,每一行代码执行过程必须等待上一行代码执行完毕后才执行。
异步调用:程序在执行时,无需等待执行的返回值可继续执行后面的代码。
显而易见,同步有依赖相关性,而异步没有,所以异步可并发执行,可提高执行效率,在相同的时间做更多的事情

Async异步调用
在SpringBoot中使用异步调用是很简单的,只需要使用@Async注解即可实现方法的异步调用
1)主启动类修改

@SpringBootApplication
@EnableAsync //开启异步调用,启用@Async注解
public class AsyncApplication {

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

}

2)@Async异步调用

@Service
public class UserService implements IUserService {

    @Async //声明异步调用
    @Override
    public void sendSms() {
        System.out.println("********send sms************   2");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("********send sms************   3");
    }
}

3)控制层测试

@RestController
public class IndexController {

    @Autowired
    private IUserService userService;

    @GetMapping("/")
    public void index(){
        System.out.println("**********************       1");

        userService.sendSms();

        System.out.println("**********************       4");
    }

}

4)测试结果:
不启动异步:

**********************       1
********send sms************   2
********send sms************   3
**********************       4

启动异步:

**********************       1
**********************       4
********send sms************   2
********send sms************   3

至此,SpringBoot实现Async异步调用完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序小达人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值