from concurrent.futures import ThreadPoolExecutor,ALL_COMPLETED,wait,as_completedimport time
def addNum(x,y): # print("test 测试阻塞{}".format(time.asctime())) time.sleep(1) return x+ydef executors(): list1=[i for i in range(1000)] list2=[j for j in range(1000,2000)] executor=ThreadPoolExecutor(max_workers=4) all_task=[executor.submit(addNum,x,y) for x,y in zip(list1,list2)] # 任务没完成的时候as_completed会阻塞,先完成的会先yield,按谁先完成输出 st=time.perf_counter() for f in as_completed(all_task): res=f.result() print("这是计算的结果{}--{}".format(res,time.asctime())) end=time.perf_counter()-st print(end)def mapExecutor(): """按顺序list的,即使先完成""" executor=ThreadPoolExecutor(max_workers=4) list1=[i for i in range(100)] list2=[j for j in range(100,200)] for res in executor.map(addNum,list1,list2): print("this is res {}--{}".format(res,time.asctime())) print("main finish")def waitExec(): executor=ThreadPoolExecutor(max_workers=4) list1=[i for i in range(10)] list2=[j for j in range(10,20)] all_task=[executor.submit(addNum,x,y) for x,y in zip(list1,list2)] #当所有任务完成后才输出结果,不然就阻塞 wait(fs=all_task,timeout=None,return_when=ALL_COMPLETED) print("主线程finish")if __name__ == '__main__': mapExecutor()