单线程:
from time import ctime,sleep
def music():
for i in range(2):
print "I was listening to music. %s" %ctime()
sleep(1)
def move():
for i in range(2):
print "I was at the movies! %s" %ctime()
sleep(5)
if __name__ == '__main__':
music()
move()
print "all over %s" %ctime()
先听了一首音乐,通过for循环来控制音乐的播放了两次,每首音乐播放需要1秒钟,sleep()来控制音乐播放的时长。接着我们又看了一场电影,
每一场电影需要5秒钟,因为太好看了,所以我也通过for循环看两遍。在整个休闲娱乐活动结束后,我通过
print "all over %s" %ctime()
看了一下当前时间,差不多该睡觉了。
运行结果:
>>=========================== RESTART ================================
>>>
I was listening to music. Thu Apr 17 10:47:08 2014
I was listening to music. Thu Apr 17 10:47:09 2014
I was at the movies! Thu Apr 17 10:47:10 2014
I was at the movies! Thu Apr 17 10:47:15 2014
all over Thu Apr 17 10:47:20 2014
#coding=utf-8
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5)
if __name__ == '__main__':
music(u'爱情买卖') #对music()和move()进行了传参处理
move(u'阿凡达')
print "all over %s" %ctime()
运行结果:
>>> ======================== RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 11:48:59 2014
I was listening to 爱情买卖. Thu Apr 17 11:49:00 2014
I was at the 阿凡达! Thu Apr 17 11:49:01 2014
I was at the 阿凡达! Thu Apr 17 11:49:06 2014
all over Thu Apr 17 11:49:11 2014
多线程:
#coding=utf-8
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
print "all over %s" %ctime()
import threading
首先导入threading 模块,这是使用多线程的前提。
threads = [] #创建了threads数组
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1) #把创建好的线程t1装到threads数组中。
创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。
接着以同样的方式创建线程t2,并把t2也装到threads数组。
for t in threads:
t.setDaemon(True)
t.start()
最后通过for循环遍历数组。(数组被装载了t1和t2两个线程)
setDaemon()
setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。
start() #始线程活动。
运行结果:
>>> ========================= RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 12:51:45 2014 I was at the 阿凡达! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014
从执行结果来看,
子线程(muisc 、move )和主线程(print "all over %s" %ctime())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。
优化程序
...
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join()
print "all over %s" %ctime()
我们只对上面的程序加了个join()方法,用于等待线程终止。
join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。
运行结果:
>>> ========================= RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 13:04:11 2014 I was at the 阿凡达! Thu Apr 17 13:04:11 2014
I was listening to 爱情买卖. Thu Apr 17 13:04:12 2014
I was at the 阿凡达! Thu Apr 17 13:04:16 2014
all over Thu Apr 17 13:04:21 2014
#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列表有多少个文件,这是为了帮助我们确定循环次数。
接着我们通过一个for循环,把list中的文件添加到线程中数组threads[]中。接着启动threads[]线程组,最后打印结束时间。
split()可以将一个字符串拆分成两部分,然后取其中的一部分。
>>> x = 'testing.py'
>>> s = x.split('.')[1]
>>> if s=='py':
print s
py
运行结果:
Start playing: 爱情买卖.mp3! Mon Apr 21 12:48:40 2014
Start playing: 阿凡达.mp4! Mon Apr 21 12:48:40 2014
Start playing: 爱情买卖.mp3! Mon Apr 21 12:48:42 2014
Start playing: 阿凡达.mp4! Mon Apr 21 12:48:45 2014
end:Mon Apr 21 12:48:50 2014
现在向list数组中添加一个文件,程序运行时会自动为其创建一个线程。
#coding=utf-8
from time import sleep, ctime
import threading
def super_player(file,time):
for i in range(2):
print 'Start playing: %s! %s' %(file,ctime())
sleep(time)
#播放的文件与播放时长
list = {'爱情买卖.mp3':3,'阿凡达.mp4':5,'我和你.mp3':4}
threads = []
files = range(len(list))
#创建线程
for file,time in list.items():
t = threading.Thread(target=super_player,args=(file,time))
threads.append(t)
if __name__ == '__main__':
#启动线程
for i in files:
threads[i].start()
for i in files:
threads[i].join()
#主线程
print 'end:%s' %ctime()
首先创建字典list ,用于定义要播放的文件及时长(秒),通过字典的items()方法来循环的取file和time,取到的这两个值用于创建线程。
接着创建super_player()函数,用于接收file和time,用于确定要播放的文件及时长。
最后是线程启动运行。运行结果:
Start playing: 爱情买卖.mp3! Fri Apr 25 09:45:09 2014
Start playing: 我和你.mp3! Fri Apr 25 09:45:09 2014
Start playing: 阿凡达.mp4! Fri Apr 25 09:45:09 2014
Start playing: 爱情买卖.mp3! Fri Apr 25 09:45:12 2014
Start playing: 我和你.mp3! Fri Apr 25 09:45:13 2014
Start playing: 阿凡达.mp4! Fri Apr 25 09:45:14 2014
end:Fri Apr 25 09:45:19 2014
#coding=utf-8
import threading
from time import sleep, ctime
class MyThread(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 super_play(file,time):
for i in range(2):
print 'Start playing: %s! %s' %(file,ctime())
sleep(time)
list = {'爱情买卖.mp3':3,'阿凡达.mp4':5}
#创建线程
threads = []
files = range(len(list))
for k,v in list.items():
t = MyThread(super_play,(k,v),super_play.__name__)
threads.append(t)
if __name__ == '__main__':
#启动线程
for i in files:
threads[i].start()
for i in files:
threads[i].join()
#主线程
print 'end:%s' %ctime()
MyThread(threading.Thread)
创建MyThread类,用于继承threading.Thread类。
__init__()
使用类的初始化方法对func、args、name等参数进行初始化。
apply()
apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典。
apply() 用法:
#不带参数的方法
>>> def say():
print 'say in'
>>> apply(say)
say in
#函数只带元组的参数
>>> def say(a,b):
print a,b
>>> apply(say,('hello','虫师'))
hello 虫师
#函数带关键字参数
>>> def say(a=1,b=2):
print a,b
>>> def haha(**kw):
apply(say,(),kw)
>>> haha(a='a',b='b')
a b
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)