当前位置: 首页 > 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("主程序结束了")
  • 运行

在这里插入图片描述

http://www.lqws.cn/news/141949.html

相关文章:

  • Python训练打卡Day42
  • 【DVWA系列】——Brute Force(暴力破解)——low
  • C++抽象类与多态实战解析
  • Python-多线程(一)
  • 2025.6.4总结
  • URL 结构说明+路由(接口)的认识
  • 卡西欧模拟器:Windows端功能强大的计算器
  • WireShark相关技巧
  • 【趣味Html】第11课:动态闪烁发光粒子五角星
  • [特殊字符] 革命性AI提示词优化平台正式开源!
  • 近期调试有感
  • 爬虫学习记录day1
  • 《短线追涨与低吸技术》速读笔记
  • 使用cephadm离线部署reef 18版并配置对接openstack
  • C语言-指针基础概念
  • Vue 生命周期全解析:从创建到销毁的完整旅程
  • OD 算法题 B卷【查找舆情热词】
  • el-amap-bezier-curve运用及线弧度设置
  • 构建高效可靠的电商 API:设计原则与实践指南
  • Oracle数据库笔记
  • 智能合约安全漏洞解析:从 Reentrancy 到 Integer Overflow
  • 嵌入式系统中常用的开源协议
  • LeetCode 热题 100 739. 每日温度
  • 修复与升级suse linux
  • Viggle:开启视频人物替换新纪元
  • 滑动智能降级:Glide优化加载性能的黑科技
  • 用布局管理器grid实现计算机界面
  • Win11系统输入时首字母丢失 - 解决方案
  • 11. 试学内容-如何理解隔离性2(原理)
  • 题海拾贝:P2347 [NOIP 1996 提高组] 砝码称重