Python创建线程的几种方式

1. 使用 threading.Thread

方式一:直接传入目标函数

import threading
import time

def task(name, delay):
    print(f"任务 {name} 开始")
    time.sleep(delay)
    print(f"任务 {name} 完成")

# 创建线程
thread1 = threading.Thread(target=task, args=("A", 2))
thread2 = threading.Thread(target=task, args=("B", 1))

# 启动线程
thread1.start()
thread2.start()

# 等待线程完成
thread1.join()
thread2.join()

print("所有任务完成")

方式二:继承 Thread 类并重写 run 方法

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, name, delay):
        super().__init__()
        self.name = name
        self.delay = delay
    
    def run(self):
        print(f"任务 {self.name} 开始")
        time.sleep(self.delay)
        print(f"任务 {self.name} 完成")

# 创建并启动线程
thread1 = MyThread("A", 2)
thread2 = MyThread("B", 1)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print("所有任务完成")

2. 使用线程池 ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor
import time

def task(name, delay):
    print(f"任务 {name} 开始")
    time.sleep(delay)
    print(f"任务 {name} 完成")
    return f"任务 {name} 结果"

# 使用线程池
with ThreadPoolExecutor(max_workers=3) as executor:
    # 提交单个任务
    future1 = executor.submit(task, "A", 2)
    future2 = executor.submit(task, "B", 1)
    
    # 获取结果
    result1 = future1.result()
    result2 = future2.result()
    print(f"结果: {result1}, {result2}")

# 使用 map 方法批量提交任务
with ThreadPoolExecutor(max_workers=2) as executor:
    results = executor.map(task, ["C", "D", "E"], [1, 2, 1])
    for result in results:
        print(f"收到结果: {result}")

3. 使用 threading.Timer 实现定时任务

import threading
import time

def delayed_task():
    print("延迟任务执行了!")

# 创建定时器,5秒后执行
timer = threading.Timer(5.0, delayed_task)
timer.start()

print("定时器已启动,等待5秒...")

4. 使用队列 (queue.Queue) 配合工作线程

import threading
import queue
import time

def worker(q):
    while True:
        task = q.get()
        if task is None:  # 终止信号
            break
        print(f"处理任务: {task}")
        time.sleep(1)
        q.task_done()

# 创建任务队列
task_queue = queue.Queue()

# 创建工作线程
threads = []
for i in range(3):
    t = threading.Thread(target=worker, args=(task_queue,))
    t.start()
    threads.append(t)

# 添加任务
for i in range(10):
    task_queue.put(f"任务-{i}")

# 等待所有任务完成
task_queue.join()

# 停止工作线程
for i in range(3):
    task_queue.put(None)

for t in threads:
    t.join()

print("所有工作完成")

总结对比

方式优点缺点适用场景
threading.Thread简单直接,控制灵活需要手动管理线程生命周期简单的多任务场景
继承 Thread面向对象,可封装复杂逻辑代码量稍多需要复用线程逻辑的场景
ThreadPoolExecutor自动管理线程池,资源利用率高配置相对复杂大量短期任务的场景
threading.Timer简单实现定时任务功能有限延迟执行或定时任务
队列+工作线程任务分发均衡,可控性强实现相对复杂生产者-消费者模式

推荐使用

  • 简单任务:直接使用 threading.Thread
  • 大量短期任务:使用 ThreadPoolExecutor
  • 复杂任务逻辑:继承 Thread
  • 任务调度:使用队列配合工作线程模式

选择哪种方式取决于具体的应用场景和需求复杂度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值