示例代码如下:
import threading
import time
class Task(threading.Thread):
def __init__(self, food):
super().__init__()
self.food = food
def run(self):
print(self.food, "开始制作")
time.sleep(2)
print(self.food, "制作完成")
def main():
food_list = ['番茄炒鸡蛋', '青椒炒牛肉']
start_time = time.time()
for food in food_list:
t = Task(food)
# 调用start才会真正创建线程, 开启线程后,会调用run方法
t.start()
end_time = time.time()
print(end_time - start_time)
if __name__ == '__main__':
main()