优化线程
代码如下:
#coding=utf-8
#优化线程:对threads.py多线程的优化
from time import sleep,ctime
import threading
def music(func):
for i in range(2):
print('I was listening to %s! %s'%(func,ctime()))
sleep(2)
def movie(func):
for i in range(2):
print('I was at the %s! %s'%(func,ctime()))
sleep(5)
#判断类型,并给对应的函数播放
def play(name):
r = name.split('.')[1]
if r=='mp3':
music(name)
elif r=='mp4':
movie(name)
else:
print("error:The format isn't recognized!")
#name_list = ['last dance.mp3',u'都挺好.mp4']
#name_list的内容数量可随意添加,但必须都加上后缀名
name_list = ['last dance.mp3',u'都挺好.mp4','test.txt']
size = len(name_list)
threads = []
for i in range(size):
t = threading.Thread(target=play,args=(name_list[i],))
threads.append(t)
if __name__ == "__main__":
#启动线程
'''
for i in threads:
i.start()
for i in threads:
i.join()'''
for i in range(size):
threads[i].start()
for i in range(size):
threads[i].join()
print("All end:",ctime())
运行结果为:
网友评论