【轉自】暱稱:Holbrook http://www.cnblogs.com/holbrook/archive/2012/02/25/2368231.html
線程的合并
python的Thread類中還提供了join()方法,使得一個線程可以等待另一個線程執行結束後再繼續運行。這個方法還可以設定一個timeout參數,避免無休止的等待。因為兩個線程順序完成,看起來象一個線程,所以稱為線程的合并。一個例子:
import threading
import random
import time
class MyThread(threading.Thread):
def run(self):
wait_time=random.randrange(1,10)
print "%s will wait %d seconds" % (self.name, wait_time)
time.sleep(wait_time)
print "%s finished!" % self.name
if __name__=="__main__":
threads = []
for i in range(5):
t = MyThread()
t.start()
threads.append(t)
print 'main thread is waitting for exit...'
for t in threads:
t.join(1)
print 'main thread finished!'
執行結果:
Thread-1 will wait 3 seconds
Thread-2 will wait 4 seconds
Thread-3 will wait 1 seconds
Thread-4 will wait 5 seconds
Thread-5 will wait 3 seconds
main thread is waitting for exit...
Thread-3 finished!
Thread-1 finished!
Thread-5 finished!
main thread finished!
Thread-2 finished!
Thread-4 finished!
對於sleep時間過長的線程(這裡是2和4),將不被等待。
後台線程
預設情況下,主線程在退出時會等待所有子線程的結束。如果希望主線程不等待子線程,而是在退出時自動結束所有的子線程,就需要設定子線程為後台線程(daemon)。方法是通過調用線程類的setDaemon()方法。如下:
import threading
import random
import time
class MyThread(threading.Thread):
def run(self):
wait_time=random.randrange(1,10)
print "%s will wait %d seconds" % (self.name, wait_time)
time.sleep(wait_time)
print "%s finished!" % self.name
if __name__=="__main__":
print 'main thread is waitting for exit...'
for i in range(5):
t = MyThread()
t.setDaemon(True)
t.start()
print 'main thread finished!'
執行結果:
main thread is waitting for exit...
Thread-1 will wait 3 seconds
Thread-2 will wait 3 seconds
Thread-3 will wait 4 seconds
Thread-4 will wait 7 seconds
Thread-5 will wait 7 seconds
main thread finished!
可以看出,主線程沒有等待子線程的執行,而直接退出。
小結
join()方法使得線程可以等待另一個線程的運行,而setDaemon()方法使得線程在結束時不等待子線程。join和setDaemon都可以改變線程之間的運行順序。