1:@EnableAsync
开启异步调用,扫描同级包,看同级包内的文件的方法上是否有@Async注解。
package com.zhaoy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2:@Async
在方法上使用。相当于这个方法重新开辟了一个线程进行执行。
package com.zhaoy.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.zhaoy.entity.User;
@Service
public class UserService {
@Async
public User getUser() throws InterruptedException {
System.out.println("3");
Thread.sleep(3000);
User user = new User();
System.out.println("4");
user.setName("zhaoyu");
user.setAge(24);
return user;
}
}