线程 -- join 功能
2020-07-27 本文已影响0人
glRu
由于多线程的执行是无序的,因此使用 join 对控制多个线程的执行顺序非常关键。
举个例子:
def T1_job():
print("T1 start\n")
for i in range(10):
time.sleep(0.1)
print("T1 finish\n")
def T2_job():
print("T2 start\n")
print("T2 finish\n")
thread_1 = threading.Thread(target=T1_job, name='T1')
thread_2 = threading.Thread(target=T2_job, name='T2')
thread_1.start() # start T1
thread_2.start() # start T2
thread_2.join() # join for T2
thread_1.join() # join for T1
print("all done\n")
T2在T1之后启动,并且因为T2任务量小会在T1之前完成;而T1也因为加了join,all done在它完成后才显示。输出结果为:
T1 start
T2 start
T2 finish
T1 finish
all done