温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python多线程怎么写

发布时间:2026-09-04 10:44:34 来源:亿速云 阅读:93 作者:小樊 栏目:编程语言

在 Python 里写“多线程”通常有两种常见方式:

  1. 使用 threading 模块(最常用)
  2. 使用 concurrent.futures.ThreadPoolExecutor(更现代、更简洁)

下面分别给你示例。


一、使用 threading 模块(基础写法)

1️⃣ 最简单的多线程示例

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():等待线程结束

2️⃣ 继承 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)

三、⚠️ 重要注意:GIL 限制

Python 的 GIL(全局解释器锁) 导致:

  • ✅ 多线程适合 I/O 密集型任务(网络、文件、数据库)
  • ❌ 不适合 CPU 密集型任务(计算、加密、图像处理)

如果是 CPU 密集型,推荐用 multiprocessing(多进程)


四、线程安全问题(简单提一下)

多个线程访问同一变量时要加锁:

lock = threading.Lock()

with lock:
    # 安全修改共享变量
    pass

五、你适合哪一种?

场景 推荐方式
简单任务 threading.Thread
批量任务 ThreadPoolExecutor
CPU 密集 multiprocessing

如果你有具体场景(比如爬虫、接口请求、文件处理),我可以给你更合适的示例代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI