主线程启动一个子线程t并等到t线程结束后才执行:
import threading
import time
def reading():
for i in range(5):
print("reading", i)
time.sleep(1)
t = threading.Thread(target = reading)
t.setDaemon(True)
t.start()
t.join()
print("The End")
运行结果为:
reading 0
reading 1
reading 2
reading 3
reading 4
The End
由此可见主线程启动子线程t执行reading函数 t.join阻塞主线程,一直等到t线程执行完毕后才结束t线程结束才执行主线程输出the end。
在子线程启动另外一个子线程,并等待子线程结束后才继续执行:
import threading
import time
def reading():
for i in range(5):
print("reading", i)
time.sleep(1)
def test():
r = threading.Thread(target=reading)
r.setDaemon(True)
r.start()
r.join()
print("test end")
t = threading.Thread(target = test)
t.setDaemon(True)
t.start()
t.join()
print("The End")
运行结果:
reading 0
reading 1
reading 2
reading 3
reading 4
test end
The End
由此可见主线程启动t线程后t.join会等待t线程结束,在test中再次启动r子线程,r子线程加入r.join而阻塞t线程,知道r进程结束,然后才显示test end,然后t线程结束再次结束t.join。主线程显示The End 结束。