在一個進程中定義多個線程
阿新 • • 發佈:2017-05-08
daemon 之前 args 設置 tar main art blog thread
import threading
from time import ctime,sleep
import time
def music(name):
print(‘listening to {name}.{time}‘.format(name=name,time=ctime()))
sleep(3)
print(‘end {time}‘.format(time=ctime()))
def blog(title):
print(‘recording the {title}.{time}‘.format(title=title,time=ctime()))
sleep(5)
print(‘end {time}‘.format(time=ctime()))
threads =[]
t1 =threading.Thread(target=music,args=(‘like‘,))
t2 =threading.Thread(target=blog,args=(‘beijing‘,))
threads.append(t1)
threads.append(t2)
if __name__ == ‘__main__‘:
# t1.setDaemon(True) #註:一定要在start之前設置.它說明在主線程是否結束不考慮
# t1線程是否運行結束,故主線程是否結束於t2線程有關
t2.setDaemon(True) #運行的結果與t1.setDaemon(True)的結果不同的然因是兩個
# 線程運行結束的時間不同
for i in threads: #運行t1和t2線程
i.start()
#t2.join()
print(‘all over %s‘ % ctime())
在一個進程中定義多個線程