python判断线程是否结束

在 Python 中,你可以使用 Thread.is_alive() 方法来判断一个线程是否还在运行。这个方法会返回一个布尔值,如果线程正在运行就会返回 True ,否则会返回 False

你可以这样使用这个方法:

import threading
def my_function():
    # do something
# 创建一个线程
thread = threading.Thread(target=my_function)
# 启动线程
thread.start()
# 判断线程是否在运行
if thread.is_alive():
    print("The thread is still running")
else:
    print("The thread has stopped")

此外,你还可以使用 join() 方法来等待线程结束,这个方法会使主线程挂起直到调用它的线程结束。你可以这样使用它:

import threading
def my_function():
    # do something
# 创建一个线程
thread = threading.Thread(target=my_function)
# 启动线程
thread.start()
# 等待线程结束
thread.join()
print("The thread has stopped")

希望这些信息能帮到你。

  •