From: http://www.cnblogs.com/holbrook/archive/2012/03/21/2410120.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都可以改变线程之间的运行顺序。