join():在子线程完成运行之前,这个子线程的父线程将一直被阻塞
import threading #线程
import time
def Beijing(n):
print('Beijing time is start %s' % time.strftime('%Y-%m-%d %X', time.localtime()))
time.sleep(2)
print('Beijing time is over %s' % time.strftime('%Y-%m-%d %X', time.localtime()))
def Shanghai(n):
print('Shanghai time is start %s' %time.strftime('%Y-%m-%d %X',time.localtime()))
time.sleep(5)
print('Shanghai time is over %s' %time.strftime('%Y-%m-%d %X',time.localtime()))
if __name__ == '__main__':
t1 = threading.Thread(target=Beijing,args=(10,))
t1.start()
t2 = threading.Thread(target=Shanghai, args=(2,))
t2.start()
t1.join() #join 等待,t1.jion 就是必须等t1运行完成后,在接着运行后面的代码
print('Done')
运行的结果是:
Beijing time is start 2018-05-29 17:37:18
Shanghai time is start 2018-05-29 17:37:18
Beijing time is over 2018-05-29 17:37:20
Done
Shanghai time is over 2018-05-29 17:37:23
# Beijing Shanghai 同时执行开始时间 然后等待2秒,运行完beijing;接着打印Done;3秒后开始打印Shanghai结束时间