說異步調(diào)用前,我們說說它對應(yīng)的同步調(diào)用。通常開發(fā)過程中,一般上我們都是同步調(diào)用,即:程序按定義的順序依次執(zhí)行的過程,每一行代碼執(zhí)行過程必須等待上一行代碼執(zhí)行完畢后才執(zhí)行。而異步調(diào)用指:程序在執(zhí)行時(shí),無需等待執(zhí)行的返回值可繼續(xù)執(zhí)行后面的代碼。顯而易見,同步有依賴相關(guān)性,而異步?jīng)]有,所以異步可并發(fā)執(zhí)行,可提高執(zhí)行效率,在相同的時(shí)間做更多的事情。
同步
程序按照定義順序依次執(zhí)行,每一行程序都必須等待上一行程序執(zhí)行完成之后才能執(zhí)行,就是在發(fā)出一個(gè)功能調(diào)用時(shí),在沒有得到結(jié)果之前,該調(diào)用就不返回。
異步
程序在順序執(zhí)行時(shí),不等待異步調(diào)用的語句返回結(jié)果就執(zhí)行后面的程序,當(dāng)一個(gè)異步過程調(diào)用發(fā)出后,調(diào)用者不能立刻得到結(jié)果。
同步代碼
service層:
1
2
3
4
5
6
|
public void test() throws interruptedexception { thread.sleep( 2000 ); for ( int i = 0 ; i < 1000 ; i++) { system.out.println( "i = " + i); } } |
controller層:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@getmapping ( "test" ) public string test() { try { thread.sleep( 1000 ); system.out.println( "主線程開始" ); for ( int j = 0 ; j < 100 ; j++) { system.out.println( "j = " + j); } asyncservice.test(); system.out.println( "主線程結(jié)束" ); return "async" ; } catch (interruptedexception e) { e.printstacktrace(); return "fail" ; } } |
瀏覽器中請求 http://localhost:8080/test
控制臺打印順序:
- 主線程開始
- 打印j循環(huán)
- 打印i循環(huán)
- 主線程結(jié)束
異步代碼
在service層的test方法上加上@async注解,同時(shí)為了是異步生效在啟動類上加上@enableasync注解
service層:
1
2
3
4
5
6
7
|
@async public void test() throws interruptedexception { thread.sleep( 2000 ); for ( int i = 0 ; i < 1000 ; i++) { system.out.println( "i = " + i); } } |
controller不變,啟動類加上@enableasync:
1
2
3
4
5
6
7
|
@springbootapplication @enableasync public class asyncapplication { public static void main(string[] args) { springapplication.run(asyncapplication. class , args); } } |
再次請求打印順序如下:
- 主線程開始
- 打印j循環(huán)
- 主線程結(jié)束
- 打印i循環(huán)
代碼: async
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000018838942