在 Python 中,使用多线程(multithreading)可以让程序并发地执行多个任务,从而提高程序的效率,尤其是在 I/O 密集型任务中,比如文件读写、网络请求等。
Python 标准库中提供了 threading
模块来支持多线程编程。下面我们会介绍如何使用 threading
模块以及多线程编程中的一些常见问题和解决方案。
1. 创建和启动线程
最基本的多线程使用方式是通过继承 threading.Thread
类或直接传递一个目标函数来创建线程。
示例 1:继承 Thread
类创建线程
import threading
import time
# 继承 Thread 类创建线程
class MyThread(threading.Thread):
def run(self):
print(f"Thread {
threading.current_thread().name} started")
time.sleep(2)
print(f"Thread {
threading.current_thread().name} finished")
# 创建线程实例
thread1 = MyThread()
thread2 = MyThread()
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
print("Main thread finished")
示例 2:通过目标函数创建线程
import threading
import time
# 定义线程任务
def task():
print(f"Thread {
threading.current_thread().name} started")
time.sleep(2)
print(f"Thread {
threading.current_thread().name} finished"