1. 程式人生 > 實用技巧 >回爐重造之重讀Windows核心程式設計-023-結束處理程式

回爐重造之重讀Windows核心程式設計-023-結束處理程式

非同步任務

  • 建立一個service類

@Service
public class AsyncService {
//通過@Async註解,告訴Spring,這是一個非同步的方法
@Async
public String hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "資料正在處理...";
}
}
  • 建立一個controller控制類

@RestController
public class AsyncController {

@Autowired//自動裝配,----匯入我們的已知的一個類,並建立一個物件
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
String str = asyncService.hello();//呼叫多執行緒類的hello()方法,效果是停止3秒,並輸出"資料正在處理..."
return str+"<hr>"+"OK!";
}
}
  • 在主方法中開啟非同步

@EnableAsync//開啟多執行緒----非同步註解功能
@SpringBootApplication
public class Springboot08TestApplication {

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