Python 最小线程 (threading.Thread) 示例

这是一个非常简单的示例,说明如何向你的 Python 脚本添加额外线程以在后台运行某些任务:

python-minimal-thread-threading-thread-example.py
from threading import Thread
import time

def extra_thread_function():
    while True:
        print("extra_thread is running")
        time.sleep(1)

extra_thread = threading.Thread(target=extra_thread_function)
extra_thread.start()

# TODO 你的主线程代码放在这里!

# 可选:等待 extra_thread 完成
extra_thread.join()

Check out similar posts by category: Python