Python多线程批量启动与执行详解

Ruby
Ruby
发布时间:2026-10-13| 6人浏览过
原创

本文详细介绍Python中使用threading模块批量启动多线程的方法。通过构建线程池、批量添加任务、统一启动及等待执行完成,实现高效并发处理。包含完整代码示例,展示如何同时处理多个耗时任务并计算总耗时,适用于需要并行执行的场景。

Python多线程批量启动概述

本文主要讲解如何在Python中批量启动多线程,通过详细的代码示例展示具体实现过程,为读者在学习或实际工作中提供参考价值。

首先,需要创建一个线程池列表,并将单个线程对象添加进去。

线程池初始化与单线程添加


threadpool = []
th = threading.Thread(target=func_name, args=func_args)
threadpool.append(th)

接着,通过循环批量将多个线程加入该线程池。

批量添加线程至线程池


for i in range(10):
  th = threading.Thread(target=func_name, args=func_args)
  threadpool.append(th)

随后,遍历线程池,依次启动所有线程并等待它们执行完毕。

启动线程与等待执行完成


for th in threadpool:
    th.start()
for th in threadpool:
  threading.Thread.join(th)

具体实现代码如下所示:

完整代码示例与耗时分析


#!/usr/bin/python3.4
# -*- coding: utf-8 -*-

import time
import threading


def matter1(music, test):
  print(test, music)
  # 假设每一首歌曲的时间是2秒
  time.sleep(2)

if __name__ == '__main__':
  # 设定我要听的歌为
  musics = ["music1", "music2", "music3"]
  test = "122678"
  # 开始时间
  start = time.time()

  threadpool = []

  # 传入多个参数
  for music in musics:
    # 传入单个参数请写成
    # args=(arg1,)
    th = threading.Thread(target=matter1, args=(music, test))
    threadpool.append(th)
  for th in threadpool:
    th.start()
  for th in threadpool:
    threading.Thread.join(th)

  # 结束时间
  end = time.time()
  print("完成的时间为:" + str(end - start))

执行结果显示,完成同时处理三首歌曲的任务耗时约2秒。

以上就是本文的全部内容,希望能为读者的学习带来帮助,欢迎继续支持本站获取更多技术资源。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。