一、异步调用
@SpringBootApplication(scanBasePackages = {"com.wuxi"}) @EnableAsync // 开启异步调用 public class Myapplication { //入口 public static void main(String[] args) { SpringApplication.run(Myapplication.class, args); } }
@Service public class AsyncService { @Async public Future<String> doTask() throws Exception { Thread.sleep(3000); System.out.println("异步线程执行完毕"); return new AsyncResult<>("线程结束"); } }
@Autowired private AsyncService asyncService; @RequestMapping("/long") public Object requestFun() throws Exception { Future<String> task = asyncService.doTask(); System.out.println("主线程方法在异步调用的方法之后,执行情况"); while (true) { if(task.isDone()){ break; } Thread.sleep(1000); } return "你好世界"; }