Python 支持多线程编程,即在一个进程中可以同时创建多个线程来执行不同的任务。多线程编程的优势在于可以使程序的执行更加高效,并且可以使用户体验更加流畅。
在 Python 中,要使用多线程编程,首先需要导入 threading
模块。然后,可以创建一个 Thread
类的实例来表示一个线程,并通过调用该实例的 start()
方法来启动线程。例如:
import threading
def worker():
print("I am a worker thread")
# Create a thread
thread = threading.Thread(target=worker)
# Start the thread
thread.start()
上面的代码创建了一个线程,该线程会执行 worker
函数。在执行完该函数后,线程会自动结束。
如果需要等待线程执行完毕后再继续执行其他任务,可以调用线程的 join()
方法,例如:
import threading
def worker():
print("I am a worker thread")
# Create a thread
thread = threading.Thread(target=worker)
# Start the thread
thread.start()
# Wait for the thread to finish
thread.join()
# Do something after the thread finishes
print("Thread has finished")
在上面的代码中,主线程会等待 thread
线程执行完毕后再继续执行。