下面,通过一个简单的例子,来把多线程和单线程执行任务的耗时做个比较
import time
import threading
# 音乐播放器
def music(func, loop):
for i in range(loop):
print("I was listening to %s the %d time! %s" % (func, i+1, time.time()))
time.sleep(2)
# 视频播放器
def movie(func, loop):
for i in range(loop):
print("I was watching %s the %d time! %s" % (func, i+1, time.time()))
time.sleep(5)
# 创建线程数组
threads = []
# 创建线程t1,并添加到线程数组
t1 = threading.Thread(target=music, args=('十年',2)) # 已经创建好的一个线程
threads.append(t1) # 追加到线程数组
# 创建线程t2,并添加到线程数组
t2 = threading.Thread(target=movie, args=('疯狂动物城', 2)) # args是一个元组
threads.append(t2)
# 创建线程t3,并添加到线程数组
# t3 = threading.Thread(target=movie, args=('少林足球', 2))
# th