threading.Thread.join()方法用于等待线程结束的实现
Python中的threading模块提供了Thread类,用于创建和管理线程。在使用多线程时,我们常常需要等待某个线程执行完成后再做其他操作,这时可以使用Thread.join()方法。
join()方法的作用是阻塞主线程,直到调用join()方法的线程执行完成。换句话说,join()方法会使主线程等待调用该方法的线程执行完成后再继续执行。
下面是join()方法的详细说明和使用例子。
join([timeout])
参数timeout是可选的。如果不指定timeout,则会一直阻塞主线程,直到调用join()方法的线程执行完成。如果指定了timeout,主线程会等待timeout秒,如果在这期间调用join()方法的线程执行完毕,则主线程会继续执行;如果超过timeout秒线程还没有执行完毕,则主线程不再等待,会继续执行其他操作。
使用例子:
import threading
import time
def run(n):
print('thread %s is running' % n)
time.sleep(2)
print('thread %s is done' % n)
# 创建两个线程
thread1 = threading.Thread(target=run, args=(1,))
thread2 = threading.Thread(target=run, args=(2,))
# 启动线程
thread1.start()
thread2.start()
# 主线程等待thread1线程执行完成后再继续执行
thread1.join()
print('main thread is executing...')
# 主线程等待thread2线程执行完成后再继续执行,等待时间为1秒
thread2.join(1)
print('main thread is done')
运行结果:
thread 1 is running
thread 2 is running
thread 1 is done
main thread is executing...
thread 2 is done
main thread is done
在上面的例子中,创建了两个线程thread1和thread2,并分别启动它们。然后主线程调用thread1.join()方法,阻塞等待thread1线程执行完成。当thread1线程执行完成后,主线程继续执行,打印"main thread is executing..."。接着主线程调用thread2.join(1)方法,等待thread2线程执行1秒钟。由于thread2线程的执行时间较长(2秒),所以在等待1秒后,主线程不再等待,继续执行其他操作,打印"main thread is done"。
可以看出,join()方法的作用是使主线程等待调用该方法的线程执行完成。可以通过不传参数或者传递超时时间的方式来控制等待时间。
