Join方法:如果一个线程在执行过程中要调用另外一个线程,并且等到其完成以后才能接着执行,
那么在调用这个线程时可以使用被调用线程的join方法。
代码如下:
import threading
import time
from time import sleep
#第一种,创建函数并且传入Thread对象中
def now():
return str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
def test(nloop, nsec):
print 'start loop', nloop, 'at:', now()
sleep(nsec)
print 'loop', nloop, 'done at:', now()
def main():
print 'starting at:',now()
threadpool = []
for i in xrange(10):
th = threading.Thread(target=test, args=(i, 2))
threadpool.append(th)
for th in threadpool:
th.start()
for th in threadpool:
threading.Thread.join(th)
print 'all Done at:', now()
if __name__ == '__name__':
main()
在程序中,最后join()方法的调用,是主线程挨个调用子线程的 join()方法。当所调用线程都执行完毕后,
主线程才会执行下面的代码。