目录
使用 concurrent.futures.ThreadPoolExecutor
前言
Python 中的 threading 模块提供了一种简单而强大的多线程编程方式,可以在程序中同时执行多个任务,从而提高程序的效率和性能。本文将详细介绍如何使用 threading 模块进行多线程编程的最佳实践,包括线程的创建、同步、通信、线程池等内容,并提供丰富的示例代码帮助更好地理解和应用这些技术。
线程的创建
在 Python 中,可以通过继承 threading.Thread 类或使用 threading.Thread 对象的方式来创建线程。下面分别介绍这两种方式。
1. 继承 threading.Thread 类
import threading
import time
class MyThread(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
print(f"Thread {self.name} is running")
time.sleep(2)
print(f"Thread {self.name} is finished")
# 创建并启动线程
thread1 = MyThread("Thread 1")
thread2 = MyThread("Thread 2")
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
print("All threads are finished")
2. 使用 threading.Thread 对象
import threading
import time
def thread_function(name):
print(f"Thread {name} is running")
time.sleep(2)
print(f"Thread {name} is finished")
# 创建并启动线程
thread1 = threading.Thread(target=thread_function, args=("Thread 1",))
thread2 = threading.Thread(target=thread_function, args=("Thread