温馨提示×

python线程join的用法是什么

小亿
90
2023-11-16 04:04:52
栏目: 编程语言

在Python中,join()方法用于等待线程完成其任务。当线程调用join()方法时,主线程将等待该线程完成执行,然后再继续执行后面的代码。

join()方法有两种用法:

  1. join()方法不带参数:调用该方法的线程将等待该线程执行完成。
import threading

def my_function():
    print("Thread started")
    # 执行线程任务
    print("Thread finished")

# 创建线程
my_thread = threading.Thread(target=my_function)

# 启动线程
my_thread.start()

# 等待线程执行完成
my_thread.join()

print("Main thread finished")

输出:

Thread started
Thread finished
Main thread finished
  1. join(timeout)方法带有一个可选的超时参数。如果指定了超时时间,那么主线程将等待指定的时间,如果线程在超时时间内没有执行完毕,则主线程会继续执行后续代码。
import threading

def my_function():
    print("Thread started")
    # 模拟长时间运行的任务
    for _ in range(5):
        pass
    print("Thread finished")

# 创建线程
my_thread = threading.Thread(target=my_function)

# 启动线程
my_thread.start()

# 等待线程执行完成,最多等待1秒
my_thread.join(1)

print("Main thread finished")

输出:

Thread started
Thread finished
Main thread finished

需要注意的是,如果主线程在调用join()方法之前,线程已经执行完成,则join()方法将立即返回,不会有任何等待。

0