在 Python 里写“多线程”通常有两种常见方式:
threading 模块(最常用)concurrent.futures.ThreadPoolExecutor(更现代、更简洁)下面分别给你示例。
threading 模块(基础写法)import threading
import time
def task(name):
for i in range(3):
print(f"{name} 正在执行 {i}")
time.sleep(1)
t1 = threading.Thread(target=task, args=("线程1",))
t2 = threading.Thread(target=task, args=("线程2",))
t1.start()
t2.start()
t1.join()
t2.join()
print("全部完成")
✅ 说明:
target:线程要执行的函数args:函数参数(必须是元组)start():启动线程join():等待线程结束Thread 类(面向对象写法)import threading
class MyThread(threading.Thread):
def run(self):
for i in range(3):
print(f"{self.name} 执行 {i}")
t = MyThread()
t.start()
t.join()
ThreadPoolExecutor(推荐)✅ 代码更简洁,适合批量任务
from concurrent.futures import ThreadPoolExecutor
import time
def task(n):
time.sleep(1)
return f"任务 {n} 完成"
with ThreadPoolExecutor(max_workers=3) as executor:
results = executor.map(task, range(5))
for r in results:
print(r)
Python 的 GIL(全局解释器锁) 导致:
如果是 CPU 密集型,推荐用 multiprocessing(多进程)
多个线程访问同一变量时要加锁:
lock = threading.Lock()
with lock:
# 安全修改共享变量
pass
| 场景 | 推荐方式 |
|---|---|
| 简单任务 | threading.Thread |
| 批量任务 | ThreadPoolExecutor |
| CPU 密集 | multiprocessing |
如果你有具体场景(比如爬虫、接口请求、文件处理),我可以给你更合适的示例代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。