上篇文章中 简单的理解了Python多线程。
从上面例子中发现线程的创建是颇为麻烦的,每创建一个线程都需要创建一个game,music等,如果创建的线程多时候这样极其不方便。下面对通过例子进行继续改进:
# -*- coding: UTF-8 -*-
from time import ctime,sleep
import threading
class DuoThread(threading.Thread):
def __init__(self,func,args,name=''):
threading.Thread.__init__(self)
self.name=name
self.func=func
self.args=args
def run(self):
apply(self.func,self.args)
def play(file,time):
for i in range(2):
print"Start playing: %s!%s"%(file,ctime())
sleep(time)
list={"name.mp3":3,"hello.mp4":5}
threads=[]
files=range(len(list))
for k,v in list.items():
t=DuoThread(play,(k,v),play.__name__)
threads.append(t)
if __name__ == '__main__':
print "Thread start %s" %ctime()
for i in files:
print "%s Threading %s" %(i,ctime())
threads[i].start()
for i in files:
threads[i].join()
print "all over %s" %ctime()