python的多线程
1.多线程的例子
import threading
#首先导入threading模块,这是使用多线程的前提
from time import ctime,sleep
def music(func):
for i in range(3):
print("I was listening to %s . %s" %(func,ctime()))
sleep(1)
def movie(func):
for i in range(3):
print("I was at the %s ! %s" %(func,ctime()))
sleep(5)
threads = []
t1 = threading.Thread(target=music,args=(u"空空如也",))
#使用threading.Thread()方法,创建线程,在这个方法中调用music方法target=music,args方法对music进行传参
threads.append(t1)
t2 = threading.Thread(target=movie,args=(u"海贼王",))
threads.append(t2)
if __name__ == "__main__":
for t in threads:
t.setDaemon(True)
#setDaemon(True)将线程声明为守护线程,必须在start()方法调用之前设置,如果不设置为守护线程程序会被无限挂机
t.start()
#start()开启线程活动
print("all over %s " %ctime())
执行结果如下
(2)
if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() t.join() print "all over %s" %ctime()
t.setDaemon(True) t.start() t.join() print "all over %s" %ctime()
join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞