@Async注解很简单

4,876 阅读1分钟

@Async注解

简单介绍

Spring为任务调度与异步方法执行提供了注解支持,通过在方法上设置@Async注解,可使得方法被异步调用。

开始使用

  1. 首先通过@EnableAsync注解,开始异步。
  2. 在方法上添加@Async注解。代码如下:
@Component
public class CountNum {
   @Async
    public void getWords() throws InterruptedException {
            for (int i = 0; i < 2; i++) {
                Thread.sleep(1000);
                System.out.println("第"+i+"次问你:你在干嘛?");
            }
    }

}
  1. 调用方法
 @RequestMapping("/")
    public String index() throws InterruptedException {
        countNum.getWords();
        Thread.sleep(500);
        System.out.println("我在吃饭");

        return student.toString()+student1.toString();
    }
  1. 运行结果
我在吃饭
第0次问你:你在干嘛?
第1次问你:你在干嘛?