示例代碼如下:
import threading
import time
from concurrent.futures import ThreadPoolExecutor
def make_food(food):
print(food, "開始制作")
time.sleep(2)
print(food, "制作完成")
return food
def get_finish_food(future):
print(future.result())
return future.result()
def main():
food_list = ['番茄炒雞蛋', '青椒炒牛肉']
# 創建2個線程
pool = ThreadPoolExecutor(max_workers=2)
for food in food_list:
future = pool.submit(make_food, food)
# 不阻塞,通過回調函數,獲取函數返回值
future.add_done_callback(get_finish_food)
if __name__ == '__main__':
main()
