name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.
args is the argument tuple for the target invocation. Defaults to ().
kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing
anything else to the thread.
之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思。因为我们在使用电脑的过程中无时无刻都在多进程和多线程。我们可以接着之前的例子继续讲。请先看我的上一篇博客。
从上面例子中发现线程的创建是颇为麻烦的,每创建一个线程都需要创建一个tx(t1、t2、...),如果创建的线程多时候这样极其不方便。下面对通过例子进行继续改进:
player.py
#coding=utf-8
from time import sleep, ctime
import threading
def muisc(func):
for i in range(2):
print 'Start playing: %s! %s' %(func,ctime())
sleep(2)
def move(func):
for i in range(2):
print 'Start playing: %s! %s' %(func,ctime())
sleep(5)
def player(name):
r = name.split('.')[1]
if r == 'mp3':
muisc(name)
else:
if r == 'mp4':
move(name)
else:
print 'error: The format is not recognized!'
list = ['爱情买卖.mp3','阿凡达.mp4']
threads = []
files = range(len(list))
#创建线程
for i in files:
t = threading.Thread(target=player,args=(list[i],))
threads.append(t)
if __name__ == '__main__':
#启动线程
for i in files:
threads[i].start()
for i in files:
threads[i].join()
#主线程
print 'end:%s' %ctime()
有趣的是我们又创建了一个player()函数,这个函数用于判断播放文件的类型。如果是mp3格式的,我们将调用music()函数,如果是mp4格式的我们调用move()函数。哪果两种格式都不是那么只能告诉用户你所提供有文件我播放不了。
然后,我们创建了一个list的文件列表,注意为文件加上后缀名。然后我们用len(list) 来计算list列表有多少个文件,这是为了帮助我们确定循环次数。










