本篇内容主要讲解“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。