threading join

发布时间 2023-05-21 14:00:19作者: 腐汝

1、什么是join

      在Python中,多线程可以用于提高程序的并发性和运行效率。当使用多个线程时,主线程需要等待所有子线程执行完毕后才能结束程序,否则子线程可能仍在运行,而主线程已经退出。

为了解决这个问题,可以使用join()方法来让主线程等待所有子线程的完成。join()方法会阻塞主线程,直到指定的线程完成工作或者超时。如果不指定超时时间,则主线程将一直阻塞,直到所有子线程都完成工作。

 

2、应用场景

join()方法是用于等待一个线程的结束。当在主线程中调用该方法时,主线程会被阻塞,直到被调用的线程执行完毕。因此,join()方法通常应用在以下场景中:

  • 让主线程在子线程完成之后再继续执行,保证线程的顺序性。
  • 在多个子线程并发执行任务的情况下,需要等待所有子线程完成后再统一处理结果。
  • 协调多个线程之间的执行顺序,保证某些操作的原子性和同步性,在这种情况下,你可以使用 join() 方法来控制线程的运行顺序。

总之,join()方法是用于协调多个线程之间的执行顺序和控制线程的顺序性的重要工具。

 

3、示例

import threading
import time

def worker():
    print("Worker thread started\n")
    time.sleep(2)
    print("Worker thread finished\n")

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("All threads finished")



结果一:
在不注释join的情况
Worker thread started

Worker thread started

Worker thread started

Worker thread started

Worker thread started

Worker thread finished

Worker thread finished

Worker thread finished
Worker thread finished


Worker thread finished

All threads finished


结果二:
在注释join的情况下
Worker thread started

Worker thread started

Worker thread started

Worker thread started

Worker thread started

All threads finished
Worker thread finished

Worker thread finished

Worker thread finished

Worker thread finished

Worker thread finished