首页 > 代码库 > 用python写多线程
用python写多线程
import threading #首先导入threading 模块,这是使用多线程的前提 from time import ctime,sleep
def music(func): for i in range(3): print "I was listening to" +func+ctime() sleep(2) def movie(func): for i in range(2): print "I was at the %s! %s" %(func,ctime()) sleep(5)
def eat_time(func): for i in range(5): print ‘l am eatting food %s. %s‘ %(func,ctime()) sleep(1)
threads = [] t1 = threading.Thread(target=music,args=(u‘爱情买卖‘,)) threads.append(t1) #创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。 t2 = threading.Thread(target=movie,args=(u‘阿凡达‘,)) threads.append(t2) t3 = threading.Thread(target=eat_time,args=(u‘爆米花‘,)) threads.append(t3) if __name__ == ‘__main__‘: for t in threads: t.setDaemon(True) #setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句后,没有等待子线程,直接就退出了,同时子线程也一同结束。 t.start() #开始线程活动 print "夜深了我要睡觉了!!!!!!!!!!!!!!!!!!!!!!!!!!!! %s" %ctime() #此句代码为主线程
运行的结果是:
I was listening to爱情买卖Wed Nov 09 22:32:16 2016 I was at the 阿凡达! Wed Nov 09 22:32:16 2016 l am eatting food 爆米花. Wed Nov 09 22:32:16 2016 夜深了我要睡觉了!!!!!!!!!!!!!!!!!!!!! !!!!!Wed Nov 09 22:32:16 2016 这是主线程 l am eatting food 爆米花. Wed Nov 09 22:32:17 2016 I was listening to爱情买卖Wed Nov 09 22:32:18 2016 l am eatting food 爆米花. Wed Nov 09 22:32:18 2016 l am eatting food 爆米花. Wed Nov 09 22:32:19 2016 I was listening to爱情买卖Wed Nov 09 22:32:20 2016 l am eatting food 爆米花. Wed Nov 09 22:32:20 2016 I was at the 阿凡达! Wed Nov 09 22:32:21 2016
如果我们把上面的程序结尾处添加t.jion()如下:
if __name__ == ‘__main__‘: for t in threads: t.setDaemon(True) t.start() t.join() print "夜深了我要睡觉了!!!!!!!!!!!!!!!!!!!!!! %s" %ctime()
运行结果:
I was listening to爱情买卖Wed Nov 09 22:52:04 2016 I was at the 阿凡达! Wed Nov 09 22:52:04 2016 l am eatting food 爆米花. Wed Nov 09 22:52:04 2016 l am eatting food 爆米花. Wed Nov 09 22:52:05 2016 I was listening to爱情买卖Wed Nov 09 22:52:06 2016 l am eatting food 爆米花. Wed Nov 09 22:52:06 2016 l am eatting food 爆米花. Wed Nov 09 22:52:07 2016 I was listening to爱情买卖Wed Nov 09 22:52:08 2016 l am eatting food 爆米花. Wed Nov 09 22:52:08 2016 I was at the 阿凡达! Wed Nov 09 22:52:09 2016 夜深了我要睡觉了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Wed Nov 09 22:52:09 2016
我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。
下面是将上面的程序进行简化!
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 of %s is not recognized!‘ %r list = [‘爱情买卖.mp3‘,‘阿凡达.mp4‘,‘在吃东西.pic‘,‘简单爱.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() threads[i].join() #主线程 print ‘end:%s‘ %ctime()
运行结果:
Start playing: 爱情买卖.mp3! Wed Nov 09 23:53:30 2016 Start playing: 爱情买卖.mp3! Wed Nov 09 23:53:32 2016 Start playing: 阿凡达.mp4! Wed Nov 09 23:53:34 2016 Start playing: 阿凡达.mp4! Wed Nov 09 23:53:39 2016 error: The format of pic is not recognized! Start playing: 简单爱.mp3! Wed Nov 09 23:53:44 2016 Start playing: 简单爱.mp3! Wed Nov 09 23:53:46 2016 Start playing: 星球大战.mp4! Wed Nov 09 23:53:48 2016 Start playing: 星球大战.mp4! Wed Nov 09 23:53:53 2016 end:Wed Nov 09 23:53:58 2016
下面我们来做一个超级播放器!
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() threads[i].join() #主线程 print ‘end:%s‘ %ctime()
运行结果:
Start playing: 爱情买卖.mp3! Thu Nov 10 00:01:57 2016 Start playing: 爱情买卖.mp3! Thu Nov 10 00:02:00 2016 Start playing: 我和你.mp3! Thu Nov 10 00:02:03 2016 Start playing: 我和你.mp3! Thu Nov 10 00:02:07 2016 Start playing: 阿凡达.mp4! Thu Nov 10 00:02:11 2016 Start playing: 阿凡达.mp4! Thu Nov 10 00:02:16 2016 end:Thu Nov 10 00:02:21 2016
下面是创建一个自己的多线程类:
import threading from time import sleep, ctime class MyThread(threading.Thread): #创建MyThread类,用于继承threading.Thread类
def __init__(self,func,args,name=‘‘): # __init__()使用类的初始化方法对func、args、name等参数进行初始化 threading.Thread.__init__(self) self.name=name self.func=func self.args=args def run(self): apply(self.func,self.args) #apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。
args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典 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() threads[i].join() #主线程 print ‘end:%s‘ %ctime()
运行结果:
Start playing: 爱情买卖.mp3! Thu Nov 10 00:10:09 2016 Start playing: 爱情买卖.mp3! Thu Nov 10 00:10:12 2016 Start playing: 阿凡达.mp4! Thu Nov 10 00:10:15 2016 Start playing: 阿凡达.mp4! Thu Nov 10 00:10:20 2016 end:Thu Nov 10 00:10:25 2016
用python写多线程
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。