springboot 的異步調用 @Async註解

     異步調用,類似我們多年前的ajax調用,局部刷新,整體不變,當然,在java的後臺的異步調用,類似於自己實現一個多線程的程序,任務開啓一個線程後由它最去執行,我們其實是不能干預太多的。。

     在實際的開發中,如果某一個方法需要異步去執行,那麼我們可以在它前面加上註解。@Async 

@SpringBootApplication
@EnableAsync
public class Application{

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

}

@RequestMapping("")
public String doTask() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
this.task1();
this.task2();
this.task3();
long currentTimeMillis1 = System.currentTimeMillis();
return "task任務總耗時:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}

@Async  
public void task1() throws InterruptedException{  
    long currentTimeMillis = System.currentTimeMillis();  
    Thread.sleep(1000);  
    long currentTimeMillis1 = System.currentTimeMillis();  
    System.out.println("task1任務耗時:"+(currentTimeMillis1-currentTimeMillis)+"ms");  
}  

@Async  
public void task2() throws InterruptedException{  
    long currentTimeMillis = System.currentTimeMillis();  
    Thread.sleep(2000);  
    long currentTimeMillis1 = System.currentTimeMillis();  
    System.out.println("task2任務耗時:"+(currentTimeMillis1-currentTimeMillis)+"ms");  
}  

    比如需要調用一個發送短信的任務,實際短信是渠道方去發的,那麼我們在把請求提交過去基本就結束了,這個時候就可以做一個異步的調用來實現。。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章