1 run()方法
1.1 单个线程
在threading.Thread()类中有run()方法。
from time importctime,sleepimportthreading#定义自己类的功能
classMyThread(threading.Thread):def __init__(self,func,args,name = ""):
threading.Thread.__init__(self)
self.func=func
self.args=args
self.name=name#调用start自动执行的函数
defrun(self):
self.func(*self.args)defplayer(song_file,time):for i in range(2):print("start player %s . %s"%(song_file,ctime()) )
sleep(time)
threads=[]
t= MyThread(player,('You and me .mp3',4),'Ipod')
threads.append(t)
t.start()
t.join()
运行
start player You and me .mp3 . Sat Apr 7 19:16:10 2018start player Youand me .mp3 . Sat Apr 7 19:16:10 2018
说明
(1)start()方法调用run()方法,而run()方法调用函数
(2)start()方法是每个线程对象必需至多调用一次,当超过1次的多次调用时,则会抛出错误;在一个单独的线程控制中,它将会调用run()方法
(3)run()方法可以在子类中重定义。标准run()方法调用回调对象作为参数传递给目标对象的构造函数。
2.2 多个线程
#多个线程
from time importctime,sleepimportthreading#定义自己类的功能
classMyThread(threading.Thread):def __init__(self,func,args,name = ""):
threading.Thread.__init__(self)
self.func=func
self.args=args
self.name=name#调用start自动执行的函数
defrun(self):
self.func(*self.args)defplayer(song_file,time):for i in range(2):print("start player %s . %s"%(song_file,ctime()) )
sleep(time)
threads=[]
d= {'body.mp3':3,"Avater.mp4":5,"You and me.mp3":6}for song_file,time ind.items():
t= MyThread(player, (song_file,time), 'Ipod')
threads.append(t)
t.start()for i inthreads:
t.join()
运行
start player You and me.mp3 . Sat Apr 7 21:42:12 2018start player Youand me.mp3 . Sat Apr 7 21:42:12 2018start player body.mp3 . Sat Apr7 21:42:12 2018start player body.mp3 . Sat Apr7 21:42:12 2018start player Avater.mp4 . Sat Apr7 21:42:12 2018start player Avater.mp4 . Sat Apr7 21:42:12 2018
注:在run()语句重写过程中经常会用到super(),具体参考Python 内置函数-super
2 daemon()
A boolean value indicating whether this thread is a daemon thread.
一个布尔值,表示该线程是否为守护线程。
这个函数的设置 t.daemon = True 必须在 t.start() 之前设置,否则会抛出RuntimeError错误。
它的初始值继承于线程创建时的默认值,主线程默认不是守护进程,因此基于主线程创建的所有线程的默认daemon均为False。
当没有生存的非守护线程时,整个Python程序将会退出。
简而言之:线程中的daemon属性,默认为False,如果设置为True,则当主线程结束后,所有线程均停止。
isDaemon(self):获取线程daemon属性状态,
setDaemon(self, daemonic):设置线程守护/非守护线程;
当设置一个线程为守护线程 t.daemon = True 或 t.setDaemon(True) ( t.start() 之前)时,就表示这个线程不重要,当主线程退出时,不用等待子线程完成可直接退出。
若想等待子线程完成后再退出,那选择默认的False即可。或者显示地调用 t.daemon = False 或者 t.setDaemon(False) ,设置线程的daemon标志。此时python会在所有非守护线程退出后才会结束(即使存在守护线程也会结束)。
示例1
daemon = False
importthreadingfrom time importsleep,ctimedeffun():print('set daemon test')
sleep(3)print('thread over')
t= threading.Thread(target=fun)#daemon默认为False,故可以不写,此处列出仅为对比说明#等价于 t.setDaemon(False)
t.daemon =False
t.start()
t.join(1)print('all over',ctime())
运行
set daemon test
all over Sun Apr8 21:13:33 2018thread over
注意:运行结果中含有threan over
示例2
importthreadingfrom time importsleep,ctimedeffun():print('set daemon test')
sleep(3)print('threan over')
t= threading.Thread(target=fun)#等价于 t.setDaemon(True)
t.daemon =True
t.start()
t.join(1)print('all over',ctime())
运行
set daemon test
all over Sun Apr8 21:16:08 2018
说明:这里没有thread over 语句,因为当主进程运行完后,而daemon = True,所以直接退出。
参考: