当前位置: 首页 > news >正文

Python-多线程(一)

多线程

  • 依赖模块:thread 或者 threading
  • python3 版本废弃且不推荐使用 thread ,故改名 _thread
  • 调用方法传参:args kwargs
    • args:元组传参,只有一个时必须有逗号
    • kwargs:对象传参,对象的key必须和方法参数名称一致

_thread (废弃)

语法:

  1. 导入模块 _thread
  2. _thread.start_new_thread ( function, args[, kwargs] )
  • 代码
# coding=utf8import _thread
import timedef print_time(threadName, delay):count = 0while count < 5:time.sleep(delay)count += 1print("%d %s: %s" % (count, threadName, time.ctime(time.time())))if __name__ == '__main__':# 创建线程try:_thread.start_new_thread(print_time, ("Thread-1", 1,))except:print("Error: unable to start thread")time.sleep(6)print('执行完了....')
  • 运行

在这里插入图片描述

threading (推荐使用)

简单模式

语法:

  1. 导入模块 threading
  2. 创建 => thread = threading.Thread(target,args/kwargs)
  3. 运行 => thread.start()
  • 代码
# 导入线程模块
import threading
import timedef sing(name,age):print('唱歌者姓名:' + name + ',年龄:' + str(age))time.sleep(2)print('正在唱歌...')def dance(name, age):print('跳舞者姓名:' + name + ',年龄:' + str(age))print('正在跳舞...')if __name__ == '__main__':# args 元组传参t1 = threading.Thread(target=sing,args=('Alice', 18))# kwargs 对象传参t2 = threading.Thread(target=dance,kwargs={'name': 'Bob', 'age': 18})t1.start()t2.start()
  • 运行

在这里插入图片描述

复杂模式

语法:

  1. 继承父类threading.Thread
  2. 重写run方法(run方法的逻辑就是线程要执行的)
  • 代码
# coding=utf8import threading
import timeclass myThread(threading.Thread):  # 继承父类threading.Threaddef __init__(self, threadID, name, counter, operate):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.counter = counterself.operate = operatedef run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数print("Starting " + self.name)print("开始 " + self.operate)time.sleep(2)print("跳舞结束了")print('Ending ' + self.name)if __name__ == '__main__':# 创建新线程thread1 = myThread(1, "Thread-1", 1,'跳舞')thread1.start()time.sleep(3)print("主程序结束了")
  • 运行

在这里插入图片描述

相关文章:

  • Qwen3与MCP协议:重塑大气科学的智能研究范式
  • JSON基础知识
  • Java框架面试题
  • 【HarmonyOS 5】游戏开发教程
  • 国标GB28181视频平台EasyGBS视频实时监控系统打造换热站全景可视化管理方案
  • 第二章 2.2 数据存储安全风险之数据存储风险分析
  • Mac 双系统
  • 如何在 React 中监听 div 的滚动事件
  • 导出onnx的两种方法
  • 在本地查看服务器上的TensorBoard
  • 2025年- H65-Lc173--347.前k个高频元素(小根堆,堆顶元素是当前堆元素里面最小的)--Java版
  • 洛谷P1591阶乘数码
  • JavaWeb简介
  • 二维 根据矩阵变换计算镜像旋转角度
  • 【LLM大模型技术专题】「入门到精通系列教程」LangChain4j与Spring Boot集成开发实战指南
  • 记录一下centos8安装nginx并部署使用
  • 使用 Python 的 psutil 库进行系统资源监控
  • Apparent connection leak detected问题排查
  • Java Lombok @Data 注解用法详解
  • Reids 如何处理缓存穿透、缓存击穿、缓存雪崩问题?
  • 世界工厂采购网站/百度搜索热度
  • 信息管理网站开发的视频教程/seo做得比较好的公司
  • 河南红旗渠建设集团网站/如何广告推广
  • 外贸公司做网站该去哪里找/网址域名查询ip地址
  • 农产品网站管理员怎么做/如何创建自己的卡网
  • wordpress管理账户/太原建站seo