Python-多线程(一)

多线程

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

_thread (废弃)

语法:

  1. 导入模块 _thread
  2. _thread.start_new_thread ( function, args[, kwargs] )
  • 代码
bash 复制代码
# coding=utf8

import _thread
import time

def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%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()
  • 代码
bash 复制代码
# 导入线程模块
import threading
import time


def 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方法的逻辑就是线程要执行的)
  • 代码
python 复制代码
# coding=utf8

import threading
import time


class myThread(threading.Thread):  # 继承父类threading.Thread
    def __init__(self, threadID, name, counter, operate):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.operate = operate

    def 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("主程序结束了")
  • 运行
相关推荐
程序员爱钓鱼11 小时前
Python编程实战 · 基础入门篇 | 变量与命名规范
后端·python
007php00711 小时前
猿辅导Java面试真实经历与深度总结(二)
java·开发语言·python·计算机网络·面试·职场和发展·golang
惊鸿.Jh11 小时前
C++可变参数模板
开发语言·python
MoRanzhi120311 小时前
Pillow 基础图像操作与数据预处理
图像处理·python·深度学习·机器学习·numpy·pillow·数据预处理
素素.陈11 小时前
向RAGFlow中上传文档到对应的知识库
开发语言·python
小宁爱Python11 小时前
Django Web 开发系列(一):视图基础与 URL 路由配置全解析
后端·python·django
空影星11 小时前
SiriKali,一款跨平台的加密文件管理器
python·编辑器·电脑·智能硬件
阿_旭11 小时前
基于深度学习的甲状腺结节智能检测分割与诊断系统【python源码+Pyqt5界面+数据集+训练代码】
人工智能·python·深度学习·甲状腺结节检测
woshihonghonga11 小时前
PyTorch矩阵乘法函数区别解析与矩阵高级索引说明——《动手学深度学习》3.6.3、3.6.4和3.6.5 (P79)
人工智能·pytorch·python·深度学习·jupyter·矩阵
AI云原生12 小时前
云原生系列Bug修复:Docker镜像无法启动的终极解决方案与排查思路
运维·服务器·python·docker·云原生·容器·bug