您好,登錄后才能下訂單哦!
本篇內容主要講解“Java同步調用和異步調用怎么實現”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Java同步調用和異步調用怎么實現”吧!
同步調用和異步調用是兩種提交任務的方式
同步調用:提交完任務后,就在原地等待任務執行完畢,拿到運行結果/返回值后再執行下一步,同步調用下任務是串行執行。
異步調用:提交完任務后,不會再原地等待任務執行完畢,直接執行下一行代碼,異步調用時并發執行。
異步調用,幾乎同時下達任務
from concurrent.futures import ProcessPoolExecutorimport os, time,random def task(x): print("%s is running" % os.getpid()) time.sleep(random.randint(1,3)) return x**2 if __name__=="__main__": p = ProcessPoolExecutor() futures = [] for i in range(10): future = p.submit(task,i)#返回計算結果 futures.append(future) p.shutdown(wait=True)#默認waiti為True 等待十個進程任務執行完,關閉進程池的入口。 for future in futures: print(future.result()) print("主")
結果為: 10760 is running10564 is running12848 is running3928 is running10564 is running12848 is running10760 is running3928 is running10760 is running10564 is running0149162536496481主
如果把p.shutdown(wait=True)去掉,則會出現結果穿插在進程中
2908 is running8092 is running10376 is running13136 is running8092 is running2908 is running018092 is running10376 is running42908 is running10376 is running9162536496481主
同步調用:
def task(x): print("%s is running" % os.getpid()) time.sleep(random.randint(1,3)) return x**2 if __name__=="__main__": p = ProcessPoolExecutor() for i in range(10): res = p.submit(task,i).result()#返回計算結果 print(res) print("主")
結果為:8360 is running0472 is running14888 is running412980 is running98360 is running16472 is running254888 is running3612980 is running498360 is running64472 is running81主
到此,相信大家對“Java同步調用和異步調用怎么實現”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。