先看一个例子,该例子没用到join。
添加一个线程,输出“start”和“finish”标记线程的开始和结束。线程added_thread和线程main同时运行,其中added_thread消耗较长的时间(通过线程sleep模拟)。mian执行结束后,added_thread才执行完毕。
import threading
import time;
def job():
print("T1 start \n")
time.sleep(1)
print("T1 finish \n")
def main():
added_thread=threading.Thread(target=job,name="T1")
added_thread.start()
print("all done\n")
if __name__ == '__main__':
main()
运行结果:
T1 start
all done
>>> T1 finish
join使得线程main等待added_thread执行完毕后才结束。
下面的例子只比上例多了一行代码added_thread.join()。
import threading
import time;
def job():
print("T1 start \n")
time.sleep(1)
print("T1 finish \n")
def main():
added_thread=threading.Thread(target=job,name="T1")
added_thread.start()
added_thread.join()
print("all done\n")
if __name__ == '__main__':
main()
执行结果:
T1 start
T1 finish
all done